问:
Symfony 3 unable to login with ajax
First, I am not using FOSUserBundle in this project. So, let's get that out of the way.

I am able to register an user, but unable to log him in.

I verified that form is posted to LoginController and that it generates the authenticationUtils object, but it stops short of generating an error, even if there is one on line below:

$error = $authUtils->getLastAuthenticationError();

Otherwise it does not generate any error. It fails silently. The _wdt continues to show as anonymous even if I provide the correct credentials.

security.yml

```<code>security:
encoders:
    UsedBundle\Entity\User:
        algorithm: bcrypt

providers:
    db_provider:
        entity:
            class: UsedBundle:User
            property: email

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: ~
        provider: db_provider
        form_login:
            username_parameter: _email
</code>```

The login controller:
UsedBundle\Controller\LoginController

```<code>namespace UsedBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;

class LoginController extends Controller
{
/**
 * @Route("/login", name="login")
 */
public function loginAction(Request $request)
{
    if ($request->isMethod('POST')) {
        var_dump($_POST);
        $authUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authUtils->getLastAuthenticationError();
        var_dump($error);
        var_dump($authUtils);
        if(isset($error)){
            $message = $error->getMessageData();
            var_dump($message);
        }
        // last username entered by the user
        $lastUsername= $authUtils->getLastUsername();

        return new JsonResponse(array(
            'last_username' => $lastUsername,
            'error'         => $error,)
        );
    }else{
        return $this->render('common/login.html.twig');
    }

}
}
</code>```

The form template:

app\Resources\Views\Common\login.html.twig

```<code>{% if error is defined and error is not null %}
{{ dump(error) }}

<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% else %}
<form action="" method="post" name="login_form" id="login_form" >
    <div class="contact" >
        <input type="email" id="email" name="_email" class="form-control" placeholder="e-mail" value=" {% if last_username is defined %}
            {{ last_username }}
        {% endif %}
        " />
    </div>

    <div class="contact" >
        <input type="password" id="password" name="_password" placeholder="mot de passe" />
    </div>

    <div>
        <button type="submit" class="sub_ok btn btn-sm" name="submit" >Valider</button>
    </div>
</form>
{% endif %}
</code>```

The User entity has the getUsername() method set up to return the email:

```<code>namespace UsedBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="UsedBundle\Repository\UserRepository")
 * @UniqueEntity(fields="email", message="Email already taken")
 * @UniqueEntity(fields="avatar", message="Username already taken")
 */
class User implements UserInterface, \Serializable
{
/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=50, unique=true)
 * @Assert\Regex(
 *      pattern="/^[A-Za-z0-9\s_\-.]{5,50}$/",
 *      message="Minimum 5 caracteres, max 50."
 *      )
 */
private $avatar;

/**
 * @ORM\Column(type="string", length=50)
 * @Assert\Regex(
 *      pattern="/^[a-zA-Z\s]{5,50}$/",
 *      message="Minimum 5 lettres, max 50."
 *      )
 */
private $name;

/**
 * @ORM\Column(type="string", length=64)
 */
private $password;

/**
 * @Assert\Length(max=4096)
 * @Assert\Regex(
 *      pattern="/^.{8,50}$/",
 *      message="Minimum 8 caracteres, max 50."
 *      )
 */
private $plainPassword;

/**
 * @ORM\Column(type="string", length=100, unique=true)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

/**
 * @ORM\Column(type="string", length=50)
 * @Assert\Regex(
 *      pattern="/^[0-9]{10,20}$/",
 *      message="Minimum 5 lettres, max 50."
 *      )
 */
private $phone;

/**
 * @ORM\Column(type="string", length=50)
 */
private $role;

/**
 * @ORM\Column(type="boolean")
 */
private $isActive;

/**
 * @ORM\Column(type="string", length=64)
 */
private $userKey;

/**
 * @ORM\Column(type="datetime")
 * @Assert\DateTime()
 */
private $userKeyTime;

/**
 * @ORM\Column(type="datetime")
 * @Assert\DateTime()
 */
private $dateReg;

/**
 * @ORM\Column(type="string", length=10)
 */
private $blogSubs;

/**
 * Many users for one city
 * @ORM\ManyToOne(targetEntity="City",inversedBy="users")
 * @ORM\JoinColumn(name="city_id", referencedColumnName="id")
 */
private $cityId;

/**
 * one visitor may correspond to one user
 *
 * @ORM\OneToOne(targetEntity="Visitor", mappedBy="userId")
 */
private $visitor;

public function __construct()
{
    $this->isActive = false;
    $this->role = 'ROLE_USER';
    //$this->blogSubs = 0;
}

public function getUsername()
{
    return $this->email;
}

public function getSalt()
{
    return null;
}

public function getPassword()
{
    return $this->password;
}

public function getRoles()
{
    return array('ROLE_USER');
}

public function eraseCredentials()
{
}

/** @see \Serializable::serialize() */
public function serialize()
{
    return serialize(array(
        $this->id,
        $this->username,
        $this->password,
        // $this->salt,
    ));
}

/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->username,
        $this->password,
        // $this->salt
    ) = unserialize($serialized);
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set avatar
 *
 * @param string $avatar
 *
 * @return User
 */
public function setAvatar($avatar)
{
    $this->avatar = $avatar;

    return $this;
}

/**
 * Get avatar
 *
 * @return string
 */
public function getAvatar()
{
    return $this->avatar;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return User
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * Set password
 *
 * @param string $password
 *
 * @return User
 */
public function setPassword($password)
{
    $this->password = $password;

    return $this;
}

/**
 * Set email
 *
 * @param string $email
 *
 * @return User
 */
public function setEmail($email)
{
    $this->email = $email;

    return $this;
}

/**
 * Get email
 *
 * @return string
 */
public function getEmail()
{
    return $this->email;
}

/**
 * Set phone
 *
 * @param string $phone
 *
 * @return User
 */
public function setPhone($phone)
{
    $this->phone = $phone;

    return $this;
}

/**
 * Get phone
 *
 * @return string
 */
public function getPhone()
{
    return $this->phone;
}

/**
 * Set isActive
 *
 * @param boolean $isActive
 *
 * @return User
 */
public function setIsActive($isActive)
{
    $this->isActive = $isActive;

    return $this;
}

/**
 * Get isActive
 *
 * @return boolean
 */
public function getIsActive()
{
    return $this->isActive;
}

/**
 * Set userKey
 *
 * @param string $email
 *
 * @return User
 */
public function setUserKey( $email )
{
    $cur_time = time();
    $this->userKey = password_hash($email.$cur_time, PASSWORD_BCRYPT )."\n";
    return $this;
}

/**
 * Get userKey
 *
 * @return string
 */
public function getUserKey()
{
    return $this->userKey;
}

/**
 * Set userKeyTime
 *
 *
 * @return User
 */
public function setUserKeyTime( $hours_added = null )
{
    if ( $hours_added === null ){
        $hours_added = 20;
        $literal_time = \DateTime::createFromFormat('Y-m-d H:i:s',date("Y-m-d H:i:s", strtotime('+' . $hours_added . ' hours')));
    }else{
        $literal_time = \DateTime::createFromFormat('Y-m-d H:i:s',date("Y-m-d H:i:s", time()));
    }
    $this->userKeyTime = $literal_time;
    return $this;
}

/**
 * Get userKeyTime
 *
 * @return \DateTime
 */
public function getUserKeyTime()
{
    return $this->userKeyTime;
}

/**
 * Get dateReg
 *
 * @return \DateTime
 */
public function getDateReg()
{
    return $this->dateReg;
}

 /**
 * Set dateReg
 *
 * @return \DateTime
 */
public function setDateReg()
{
    $literal_time = \DateTime::createFromFormat('Y-m-d H:i:s',date("Y-m-d H:i:s"));
    $this->dateReg = $literal_time;
    return $this;
}

/**
 * Set role
 *
 * @param string $role
 *
 * @return User
 */
public function setRole($role)
{
    $this->role = $role;

    return $this;
}

/**
 * Get role
 *
 * @return string
 */
public function getRole()
{
    return $this->role;
}

/**
 * Set blogSubs
 *
 * @param string $blogSubs
 *
 * @return User
 */
public function setBlogSubs($blogSubs)
{
    $this->blogSubs = $blogSubs;

    return $this;
}

/**
 * Get blogSubs
 *
 * @return string
 */
public function getBlogSubs()
{
    return $this->blogSubs;
}

/**
 * Get plainPassword
 *
 * @return string
 */
public function getPlainPassword()
{
    return $this->plainPassword;
}

/**
 * Set cityId
 *
 * @param \UsedBundle\Entity\City $cityId
 *
 * @return User
 */
public function setCityId(\UsedBundle\Entity\City $cityId = null)
{
    $this->cityId = $cityId;

    return $this;
}

/**
 * Get cityId
 *
 * @return \UsedBundle\Entity\City
 */
public function getCityId()
{
    return $this->cityId;
}

/**
 * Set models
 *
 * @param \UsedBundle\Entity\Visitor $models
 *
 * @return User
 */
public function setModels(\UsedBundle\Entity\Visitor $models = null)
{
    $this->models = $models;

    return $this;
}

/**
 * Get models
 *
 * @return \UsedBundle\Entity\Visitor
 */
public function getModels()
{
    return $this->models;
}

/**
 * Set visitor
 *
 * @param \UsedBundle\Entity\Visitor $visitor
 *
 * @return User
 */
public function setVisitor(\UsedBundle\Entity\Visitor $visitor = null)
{
    $this->visitor = $visitor;

    return $this;
}

/**
 * Get visitor
 *
 * @return \UsedBundle\Entity\Visitor
 */
public function getVisitor()
{
    return $this->visitor;
}
}
</code>```

The form is submitted via Ajax, as follows:

```<code>     $(document).ready(function() {
    $('#login_form').submit(function(e) {
            var str = $("#login_form").serialize();
            $.ajax({
                url: "/login",
                type: "POST",
                dataType: "json",
                data: str,
                success: function(data) {
                    alert(data);
                }
        e.preventDefault(); //STOP default action
        });
    });
});
</code>```

I am adding the output below from Firebug. I am not exactly sure how it came about, but it shows the role property empty. Still not sure why. All users have ROLE_USER on the db

```<code>  object(Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken)#2384 (6) {
["credentials":"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":private]=>
string(8) "senha444"
["providerKey":"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":private]=>
string(4) "main"
["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
string(22) "myemail@gmail.com"
["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
bool(false)
["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
</code>```

答:
This would not work as set up above. Symfony does not play well with Ajax, so one needs to customize the login.

I have added an answer on this question with the whole setup.

Title: Symfony 3 unable to login with ajax

Body:
First, I am not using FOSUserBundle in this project. So, let's get that out of the way.

I am able to register an user, but unable to log him in.

I verified that form is posted to LoginController and that it generates the authenticationUtils object, but it stops short of generating an error, even if there is one on line below:

$error = $authUtils->getLastAuthenticationError();

Otherwise it does not generate any error. It fails silently. The _wdt continues to show as anonymous even if I provide the correct credentials.

security.yml

security:
encoders:
    UsedBundle\Entity\User:
        algorithm: bcrypt

providers:
    db_provider:
        entity:
            class: UsedBundle:User
            property: email

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

    main:
        anonymous: ~
        provider: db_provider
        form_login:
            username_parameter: _email

The login controller:
UsedBundle\Controller\LoginController

namespace UsedBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;

class LoginController extends Controller
{
/**
 * @Route("/login", name="login")
 */
public function loginAction(Request $request)
{
    if ($request->isMethod('POST')) {
        var_dump($_POST);
        $authUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authUtils->getLastAuthenticationError();
        var_dump($error);
        var_dump($authUtils);
        if(isset($error)){
            $message = $error->getMessageData();
            var_dump($message);
        }
        // last username entered by the user
        $lastUsername= $authUtils->getLastUsername();

        return new JsonResponse(array(
            'last_username' => $lastUsername,
            'error'         => $error,)
        );
    }else{
        return $this->render('common/login.html.twig');
    }

}
}

The form template:

app\Resources\Views\Common\login.html.twig

{% if error is defined and error is not null %}
{{ dump(error) }}

{{ error.messageKey|trans(error.messageData, 'security') }}

{% else %}
<form action="" method="post" name="login_form" id="login_form" >

        <input type="email" id="email" name="_email" class="form-control" placeholder="e-mail" value=" {% if last_username is defined %}
            {{ last_username }}
        {% endif %}
        " />

        <input type="password" id="password" name="_password" placeholder="mot de passe" />

        <button type="submit" class="sub_ok btn btn-sm" name="submit" >Valider</button>

</form>
{% endif %}

The User entity has the getUsername() method set up to return the email:

namespace UsedBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="UsedBundle\Repository\UserRepository")
 * @UniqueEntity(fields="email", message="Email already taken")
 * @UniqueEntity(fields="avatar", message="Username already taken")
 */
class User implements UserInterface, \Serializable
{
/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=50, unique=true)
 * @Assert\Regex(
 *      pattern="/^[A-Za-z0-9\s_\-.]{5,50}$/",
 *      message="Minimum 5 caracteres, max 50."
 *      )
 */
private $avatar;

/**
 * @ORM\Column(type="string", length=50)
 * @Assert\Regex(
 *      pattern="/^[a-zA-Z\s]{5,50}$/",
 *      message="Minimum 5 lettres, max 50."
 *      )
 */
private $name;

/**
 * @ORM\Column(type="string", length=64)
 */
private $password;

/**
 * @Assert\Length(max=4096)
 * @Assert\Regex(
 *      pattern="/^.{8,50}$/",
 *      message="Minimum 8 caracteres, max 50."
 *      )
 */
private $plainPassword;

/**
 * @ORM\Column(type="string", length=100, unique=true)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

/**
 * @ORM\Column(type="string", length=50)
 * @Assert\Regex(
 *      pattern="/^[0-9]{10,20}$/",
 *      message="Minimum 5 lettres, max 50."
 *      )
 */
private $phone;

/**
 * @ORM\Column(type="string", length=50)
 */
private $role;

/**
 * @ORM\Column(type="boolean")
 */
private $isActive;

/**
 * @ORM\Column(type="string", length=64)
 */
private $userKey;

/**
 * @ORM\Column(type="datetime")
 * @Assert\DateTime()
 */
private $userKeyTime;

/**
 * @ORM\Column(type="datetime")
 * @Assert\DateTime()
 */
private $dateReg;

/**
 * @ORM\Column(type="string", length=10)
 */
private $blogSubs;

/**
 * Many users for one city
 * @ORM\ManyToOne(targetEntity="City",inversedBy="users")
 * @ORM\JoinColumn(name="city_id", referencedColumnName="id")
 */
private $cityId;

/**
 * one visitor may correspond to one user
 *
 * @ORM\OneToOne(targetEntity="Visitor", mappedBy="userId")
 */
private $visitor;

public function __construct()
{
    $this->isActive = false;
    $this->role = 'ROLE_USER';
    //$this->blogSubs = 0;
}

public function getUsername()
{
    return $this->email;
}

public function getSalt()
{
    return null;
}

public function getPassword()
{
    return $this->password;
}

public function getRoles()
{
    return array('ROLE_USER');
}

public function eraseCredentials()
{
}

/** @see \Serializable::serialize() */
public function serialize()
{
    return serialize(array(
        $this->id,
        $this->username,
        $this->password,
        // $this->salt,
    ));
}

/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->username,
        $this->password,
        // $this->salt
    ) = unserialize($serialized);
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set avatar
 *
 * @param string $avatar
 *
 * @return User
 */
public function setAvatar($avatar)
{
    $this->avatar = $avatar;

    return $this;
}

/**
 * Get avatar
 *
 * @return string
 */
public function getAvatar()
{
    return $this->avatar;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return User
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * Set password
 *
 * @param string $password
 *
 * @return User
 */
public function setPassword($password)
{
    $this->password = $password;

    return $this;
}

/**
 * Set email
 *
 * @param string $email
 *
 * @return User
 */
public function setEmail($email)
{
    $this->email = $email;

    return $this;
}

/**
 * Get email
 *
 * @return string
 */
public function getEmail()
{
    return $this->email;
}

/**
 * Set phone
 *
 * @param string $phone
 *
 * @return User
 */
public function setPhone($phone)
{
    $this->phone = $phone;

    return $this;
}

/**
 * Get phone
 *
 * @return string
 */
public function getPhone()
{
    return $this->phone;
}

/**
 * Set isActive
 *
 * @param boolean $isActive
 *
 * @return User
 */
public function setIsActive($isActive)
{
    $this->isActive = $isActive;

    return $this;
}

/**
 * Get isActive
 *
 * @return boolean
 */
public function getIsActive()
{
    return $this->isActive;
}

/**
 * Set userKey
 *
 * @param string $email
 *
 * @return User
 */
public function setUserKey( $email )
{
    $cur_time = time();
    $this->userKey = password_hash($email.$cur_time, PASSWORD_BCRYPT )."\n";
    return $this;
}

/**
 * Get userKey
 *
 * @return string
 */
public function getUserKey()
{
    return $this->userKey;
}

/**
 * Set userKeyTime
 *
 *
 * @return User
 */
public function setUserKeyTime( $hours_added = null )
{
    if ( $hours_added === null ){
        $hours_added = 20;
        $literal_time = \DateTime::createFromFormat('Y-m-d H:i:s',date("Y-m-d H:i:s", strtotime('+' . $hours_added . ' hours')));
    }else{
        $literal_time = \DateTime::createFromFormat('Y-m-d H:i:s',date("Y-m-d H:i:s", time()));
    }
    $this->userKeyTime = $literal_time;
    return $this;
}

/**
 * Get userKeyTime
 *
 * @return \DateTime
 */
public function getUserKeyTime()
{
    return $this->userKeyTime;
}

/**
 * Get dateReg
 *
 * @return \DateTime
 */
public function getDateReg()
{
    return $this->dateReg;
}

 /**
 * Set dateReg
 *
 * @return \DateTime
 */
public function setDateReg()
{
    $literal_time = \DateTime::createFromFormat('Y-m-d H:i:s',date("Y-m-d H:i:s"));
    $this->dateReg = $literal_time;
    return $this;
}

/**
 * Set role
 *
 * @param string $role
 *
 * @return User
 */
public function setRole($role)
{
    $this->role = $role;

    return $this;
}

/**
 * Get role
 *
 * @return string
 */
public function getRole()
{
    return $this->role;
}

/**
 * Set blogSubs
 *
 * @param string $blogSubs
 *
 * @return User
 */
public function setBlogSubs($blogSubs)
{
    $this->blogSubs = $blogSubs;

    return $this;
}

/**
 * Get blogSubs
 *
 * @return string
 */
public function getBlogSubs()
{
    return $this->blogSubs;
}

/**
 * Get plainPassword
 *
 * @return string
 */
public function getPlainPassword()
{
    return $this->plainPassword;
}

/**
 * Set cityId
 *
 * @param \UsedBundle\Entity\City $cityId
 *
 * @return User
 */
public function setCityId(\UsedBundle\Entity\City $cityId = null)
{
    $this->cityId = $cityId;

    return $this;
}

/**
 * Get cityId
 *
 * @return \UsedBundle\Entity\City
 */
public function getCityId()
{
    return $this->cityId;
}

/**
 * Set models
 *
 * @param \UsedBundle\Entity\Visitor $models
 *
 * @return User
 */
public function setModels(\UsedBundle\Entity\Visitor $models = null)
{
    $this->models = $models;

    return $this;
}

/**
 * Get models
 *
 * @return \UsedBundle\Entity\Visitor
 */
public function getModels()
{
    return $this->models;
}

/**
 * Set visitor
 *
 * @param \UsedBundle\Entity\Visitor $visitor
 *
 * @return User
 */
public function setVisitor(\UsedBundle\Entity\Visitor $visitor = null)
{
    $this->visitor = $visitor;

    return $this;
}

/**
 * Get visitor
 *
 * @return \UsedBundle\Entity\Visitor
 */
public function getVisitor()
{
    return $this->visitor;
}
}

The form is submitted via Ajax, as follows:

     $(document).ready(function() {
    $('#login_form').submit(function(e) {
            var str = $("#login_form").serialize();
            $.ajax({
                url: "/login",
                type: "POST",
                dataType: "json",
                data: str,
                success: function(data) {
                    alert(data);
                }
        e.preventDefault(); //STOP default action
        });
    });
});

I am adding the output below from Firebug. I am not exactly sure how it came about, but it shows the role property empty. Still not sure why. All users have ROLE_USER on the db

  object(Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken)#2384 (6) {
["credentials":"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":private]=>
string(8) "senha444"
["providerKey":"Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken":private]=>
string(4) "main"
["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
string(22) "myemail@gmail.com"
["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}
["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
bool(false)
["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=>
array(0) {
}


来源: stackexchange

问:
a regex to parse BEM class selector with javascript
here my problem :

I want to split a string into an array of object.
My string is a BEM class selector like so :

where my string (without dot) would be splitted by matching '__' and '--'.

foo-bar--baz__foo--bar = ['foo-bar', '--baz', '__foo', '--bar']

foo-bar--baz = ['foo-bar', '--baz']

foo-bar__bar--baz = ['foo-bar', '__bar', '--baz']

foo = ['foo']

I tried with the following regex :

```<code>const regex = /([a-zA-Z0-9']+)(--[a-zA-Z0-9']+)(__[a-zA-Z0-9']+)/g;

while (match = reg.exec(string)) {
    var group1 = match[1];
    var group2 = match[2];
    var group3 = match[3];

    console.log(group1+'; '+group2+'; '+group3);
}
</code>```

but foo-bar--baz__foo--bar only output:

```<code>foo-bar --baz __foo
</code>```

and not the last --bar…

I cannot figure out why.

Also, maybe a better overall solution exist to solve my problem…

Thank's for the help

ContentLicense: CC BY-SA 3.0

Body:
here my problem :

I want to split a string into an array of object.
My string is a BEM class selector like so :

where my string (without dot) would be splitted by matching '__' and '--'.

foo-bar--baz__foo--bar = ['foo-bar', '--baz', '__foo', '--bar']

foo-bar--baz = ['foo-bar', '--baz']

foo-bar__bar--baz = ['foo-bar', '__bar', '--baz']

foo = ['foo']

I tried with the following regex :

const regex = /([a-zA-Z0-9']+)(--[a-zA-Z0-9']+)(__[a-zA-Z0-9']+)/g;

while (match = reg.exec(string)) {
    var group1 = match[1];
    var group2 = match[2];
    var group3 = match[3];

    console.log(group1+'; '+group2+'; '+group3);
}

but foo-bar--baz__foo--bar only output:

foo-bar --baz __foo

and not the last --bar…

I cannot figure out why.

Also, maybe a better overall solution exist to solve my problem…

Thank's for the help

Body:
try this : ([a-zA-Z0-9^]+[-]?[a-zA-Z0-9^]+)(?:--|__)([a-zA-Z0-9^]+[-]?[a-zA-Z0-9^]+)

https://regex101.com/r/Xz7MWQ/1


问:
PHP session side-effect warning - how to get solve?
I'm fairly new to php, and am sure this is easy, but I'd like to do it the right way. I have this script:

```<code><?php
if ($_POST["username"]=="") {
    include($_SERVER['DOCUMENT_ROOT'] ."/login.inc.php");
} else {
    $username=$_POST["username"];
    $password=$_POST["password"];
    session_start();
    if ($username=="bob" AND $password=="123"){ $permission="yes";}
    $username=$_POST["username"];
    session_register("permission");
    session_register("username");

    if ($permission=="yes"){
        // Show stuff
    }
}
?>
</code>```

Excuse the funky formatting of my code - can't seem to get it to show properly.

So, I keep getting this error:

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively in Unknown on line 0

Which I'm assuming means I need to change one of my variable names so it doesn't conflict with the session variable right? That's what I read, but I'm not sure which one to change.

Can anyone help / show me please?

Thanks

osu

答:
You better start on getting rid of deprecated functions such as session_register().

Use the $_SESSION array, e.g.

```<code>$_SESSION['username'] = $_POST['username'];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm fairly new to php, and am sure this is easy, but I'd like to do it the right way. I have this script:

<?php
if ($_POST["username"]=="") {
    include($_SERVER['DOCUMENT_ROOT'] ."/login.inc.php");
} else {
    $username=$_POST["username"];
    $password=$_POST["password"];
    session_start();
    if ($username=="bob" AND $password=="123"){ $permission="yes";}
    $username=$_POST["username"];
    session_register("permission");
    session_register("username");

    if ($permission=="yes"){
        // Show stuff
    }
}
?>

Excuse the funky formatting of my code - can't seem to get it to show properly.

So, I keep getting this error:

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively in Unknown on line 0

Which I'm assuming means I need to change one of my variable names so it doesn't conflict with the session variable right? That's what I read, but I'm not sure which one to change.

Can anyone help / show me please?

Thanks

osu

Body:
You better start on getting rid of deprecated functions such as session_register().

Use the $_SESSION array, e.g.

$_SESSION['username'] = $_POST['username'];


问:
Remove undefined properties from object
I would like to recursively clean any fields which are undefined, or have an empty object as parent like this following:

Example:

```<code>{
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
}
</code>```

I am expecting the following result :

```<code>{
  "g": {
    "h": 'I',
  },
  "k": 'L',
  "m": {
    "p": 'toto'
  }
}
</code>```

Thank you for your help

答:
function filter(obj) {
  for (var key in obj) {
    if (obj[key] === undefined) {
      delete obj[key];
      continue;
    }
    if (obj[key] && typeof obj[key] === "object") {
      filter(obj[key]);
      if (!Object.keys(obj[key]).length) {
        delete obj[key];
      }
    }
  }
  return obj;
}

var data = {
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    "f": undefined,
  },
  "g": {
    "h": 'I',
    "j": undefined,
  },
  "k": "L",
  "m": {
    "n": {
      "o": {
        "z": undefined,
      }
    },
    "p": 'toto'
  }
};

console.log(filter(data));```

Simply delete these keys and iterate recursively.

Title: Remove undefined properties from object

Body:
I would like to recursively clean any fields which are undefined, or have an empty object as parent like this following:

Example:

{
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
}

I am expecting the following result :

{
  "g": {
    "h": 'I',
  },
  "k": 'L',
  "m": {
    "p": 'toto'
  }
}

Thank you for your help

Body:
function filter(obj) {
  for (var key in obj) {
    if (obj[key] === undefined) {
      delete obj[key];
      continue;
    }
    if (obj[key] && typeof obj[key] === "object") {
      filter(obj[key]);
      if (!Object.keys(obj[key]).length) {
        delete obj[key];
      }
    }
  }
  return obj;
}

var data = {
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    "f": undefined,
  },
  "g": {
    "h": 'I',
    "j": undefined,
  },
  "k": "L",
  "m": {
    "n": {
      "o": {
        "z": undefined,
      }
    },
    "p": 'toto'
  }
};

console.log(filter(data));

Simply delete these keys and iterate recursively.


问:
Succint way of handling missing observations in numpy.cov?
As the title suggests, I'm wondering whether there's a succinct way for handling missing data when calculating covariance matrices in Python/pandas.
Consider the dataframe

```<code>df = pd.DataFrame({'var1': [1,2,3, np.nan, 5, np.nan], 'var2': [1, 1.5, 2, 2.5, np.nan, 3.5]})
</code>```

If we were to simply do np.cov(df.var1.dropna(), df.var2.dropna()), we'd get an error as there are a different number of missing values in columns one and two.
Two ways of getting around this I found were:

```<code>rowind = list(set(df.var1.dropna().index).intersection(set(df.var2.dropna().index)))
</code>```

and

```<code>rowind = (~np.isnan(data.resid1f1)) & (~np.isnan(data.resid1f2))
</code>```

and then computing np.cov(df.loc[rowind, "var1"], df.loc[rowind, "var2"]). I am however wondering whether there's some built-in function somewhere that could do this in a less verbose way.

答:
I make the below gist to reproduce and exemplify that difference, I hope that could be useful in this discussion:

```<code># =============================================================================
# NUMPY VS PANDAS: DIFFERENT ESTIMATION OF COVARIANCE IN PRESENCE OF NAN VALUES
# =============================================================================
# data with nan values
M = np.random.randn(10,2)
# add missing values
M[0,0] = np.nan
M[1,1] = np.nan

# Covariance matrix calculations
# ==============================
# numpy
# -----
masked_arr = np.ma.array(M, mask=np.isnan(M))
cov_numpy = np.ma.cov(masked_arr, rowvar=0, allow_masked=True, ddof=1).data

# pandas
# ------
cov_pandas = pd.DataFrame(M).cov(min_periods=0).values
</code>```

The below shows the example of the calcs:

```<code># Homemade covariance coefficient calculation
# (what each of them is actually doing)
# =============================================
# select elements to estimate the element 0,1 in the covariance matrix
x = M[:,0]
y = M[:,1]

mask_x = ~np.isnan(x)
mask_y = ~np.isnan(y)
mask_common = mask_x & mask_y

# numpy
# -----
xn = x-np.mean(x[mask_x])
yn = y-np.mean(y[mask_y])
cov_np = sum(a*b for a,b,c in zip(xn,yn, mask_common) if c)/(np.sum(mask_common)-1)

# pandas
# ------
xn = x-np.mean(x[mask_common])
yn = y-np.mean(y[mask_common])
cov_pd = sum(a*b for a,b,c in zip(xn,yn, mask_common) if c)/(np.sum(mask_common)-1)
</code>```

Note that the main difference is on how to apply the mean function over each variables.

source: https://gist.github.com/mmngreco/bd86213d9ccd8ddc61683a853ce2fced

Edit: I added an issue in pandas:

https://github.com/pandas-dev/pandas/issues/16837

Body:
As the title suggests, I'm wondering whether there's a succinct way for handling missing data when calculating covariance matrices in Python/pandas.
Consider the dataframe

df = pd.DataFrame({'var1': [1,2,3, np.nan, 5, np.nan], 'var2': [1, 1.5, 2, 2.5, np.nan, 3.5]})

If we were to simply do np.cov(df.var1.dropna(), df.var2.dropna()), we'd get an error as there are a different number of missing values in columns one and two.
Two ways of getting around this I found were:

rowind = list(set(df.var1.dropna().index).intersection(set(df.var2.dropna().index)))

and

rowind = (~np.isnan(data.resid1f1)) & (~np.isnan(data.resid1f2))

and then computing np.cov(df.loc[rowind, "var1"], df.loc[rowind, "var2"]). I am however wondering whether there's some built-in function somewhere that could do this in a less verbose way.

Body:
I make the below gist to reproduce and exemplify that difference, I hope that could be useful in this discussion:

# =============================================================================
# NUMPY VS PANDAS: DIFFERENT ESTIMATION OF COVARIANCE IN PRESENCE OF NAN VALUES
# =============================================================================
# data with nan values
M = np.random.randn(10,2)
# add missing values
M[0,0] = np.nan
M[1,1] = np.nan

# Covariance matrix calculations
# ==============================
# numpy
# -----
masked_arr = np.ma.array(M, mask=np.isnan(M))
cov_numpy = np.ma.cov(masked_arr, rowvar=0, allow_masked=True, ddof=1).data

# pandas
# ------
cov_pandas = pd.DataFrame(M).cov(min_periods=0).values

The below shows the example of the calcs:

# Homemade covariance coefficient calculation
# (what each of them is actually doing)
# =============================================
# select elements to estimate the element 0,1 in the covariance matrix
x = M[:,0]
y = M[:,1]

mask_x = ~np.isnan(x)
mask_y = ~np.isnan(y)
mask_common = mask_x & mask_y

# numpy
# -----
xn = x-np.mean(x[mask_x])
yn = y-np.mean(y[mask_y])
cov_np = sum(a*b for a,b,c in zip(xn,yn, mask_common) if c)/(np.sum(mask_common)-1)

# pandas
# ------
xn = x-np.mean(x[mask_common])
yn = y-np.mean(y[mask_common])
cov_pd = sum(a*b for a,b,c in zip(xn,yn, mask_common) if c)/(np.sum(mask_common)-1)

Note that the main difference is on how to apply the mean function over each variables.

source: https://gist.github.com/mmngreco/bd86213d9ccd8ddc61683a853ce2fced

Edit: I added an issue in pandas:

https://github.com/pandas-dev/pandas/issues/16837


问:
Encoding problems while extracting NSDictionary
I have a JSON file with texts and titles. Titles are in English language, but texts sometimes include cyrillic symbols. When I extract JSON to NSDictionary everything seems to be good, because log shows me english and UTF  symbols:

\U00c8\U00f1\U00f2\U00ee\U00f0\U00e8\U00df about...

But when I try to get a string from NSDictionary with this value it gives me strange symbols:

Èñòîðèß about...

It seems like there is everything allright before I try to extract any specific value from the dictionary. So I need help to understand how to get the same exact (English and UTF symbols) value which shows me when I NSLog the whole dictionary.

This is how I get the value now: NSLog(@"text: %@", dict[@"results"][0][@"text"]);

答:
It seems, you haven't encoded your data properly. See your json file in UTF-8:

That's why you can not decode it into normal NSString


问:
Request.Form for DropDownList
I have on my view:

```<code></td>
  <td class="span-8 last">
    <div class="editor-label">
        <label for="Traslado_Movimiento_UbicacionFuncional_Id">Ubicación Funcional</label>
    </div>
     <div class="editor-field">
       <select id="Traslado_Movimiento_UbicacionFuncional_Id"                 name="Traslado.Movimiento.UbicacionFuncional_Id"><option value=""> -- Seleccione -- </option>
          </select>
    </div>
</td>
</code>```

And I want to get the selected value on the select.

On my controller I wrote:

```<code>string selected = Request.Form["Traslado_Movimiento_UbicacionFuncional_Id"];
</code>```

But selected is always NULL....

Please, help!

Thx

答: As mentioned, you would need to add the runat="server" attribute. But why are you using the HTML select control if you want to use this from server code? It seems to make a lot more sense to use the ASP.NET combobox.

Title: Request.Form for DropDownList

Body:
I have on my view:

        Ubicación Funcional

       <select id="Traslado_Movimiento_UbicacionFuncional_Id"                 name="Traslado.Movimiento.UbicacionFuncional_Id"><option value=""> -- Seleccione -- </option>
          </select>

And I want to get the selected value on the select.

On my controller I wrote:

string selected = Request.Form["Traslado_Movimiento_UbicacionFuncional_Id"];

But selected is always NULL....

Please, help!

Thx


问:
How to choose what axes to plot on in Pandas (Python)
How do I select what axes to plot on in pandas?

For example, if I were graphing a countplot in seaborn, I would have written the following:

sns.countplot(females_xt, ax = axes[0][0])

However, I'm not sure how to do this with pandas' plotting capabilities. Any help would be appreciated!

Thanks

答:
It is the same parameter ax in pandas.dataframe.plot like:

```<code>female_xt.plot(kind ='bar',stacked = True,ax=my_ax)
</code>```

Body:
It is the same parameter ax in pandas.dataframe.plot like:

female_xt.plot(kind ='bar',stacked = True,ax=my_ax)


问:
iOS - How can I get the IndexPath of the last item in a tableview?
I would like to automatically scroll to the end of a table view.

```<code>[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
</code>```

Given that I know how many item are in the tableview using:

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
</code>```

How can I get the IndexPath * to the last item in this tableView? This is needed so that I can provide it as an argument to scrollToRowAtIndexPath:atScrollPosition:animated

Thanks!

答:
It seems like all the solutions don't consider that the last section may have no rows at all. So here is a function which returns the last row in a last non-empty section:

Swift 3:

```<code>extension UITableViewDataSource {
    func lastIndexPath(_ tableView: UITableView) -> IndexPath? {
        guard let sections = self.numberOfSections?(in: tableView) else { return nil }
        for section in stride(from: sections-1, through: 0, by: -1) {
            let rows = self.tableView(tableView, numberOfRowsInSection: section)
            if rows > 0 {
                return IndexPath(row: rows - 1, section: section)
            }
        }
        return nil
    }
}
</code>```

Example:

```<code>class ViewController: UIViewController {

    //...

    func scrollToLastRow() {
        if let indexPath = lastIndexPath(tableView) {
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
}

extension ViewController: UITableViewDataSource {
    //required data source methods
}
</code>```

Body:
I would like to automatically scroll to the end of a table view.

[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

Given that I know how many item are in the tableview using:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

How can I get the IndexPath * to the last item in this tableView? This is needed so that I can provide it as an argument to scrollToRowAtIndexPath:atScrollPosition:animated

Thanks!

Body:
It seems like all the solutions don't consider that the last section may have no rows at all. So here is a function which returns the last row in a last non-empty section:

Swift 3:

extension UITableViewDataSource {
    func lastIndexPath(_ tableView: UITableView) -> IndexPath? {
        guard let sections = self.numberOfSections?(in: tableView) else { return nil }
        for section in stride(from: sections-1, through: 0, by: -1) {
            let rows = self.tableView(tableView, numberOfRowsInSection: section)
            if rows > 0 {
                return IndexPath(row: rows - 1, section: section)
            }
        }
        return nil
    }
}

Example:

class ViewController: UIViewController {

    //...

    func scrollToLastRow() {
        if let indexPath = lastIndexPath(tableView) {
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
}

extension ViewController: UITableViewDataSource {
    //required data source methods
}


问:
Serialize as object using json.net
I want certain properties to be serialized as 'objects' and not strings. E.g.

{"onClickHandler": OnClickHandler,
  "onMouseOut": OnMouseOutHandler}

The class def is like this:

```<code>public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}
</code>```

Currently it comes out as:

handlers: {"onClickHandler": "OnClickHandler",
  "onMouseOut": "OnMouseOutHandler"}

As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. By emitting them within quotes, they are not interpreted as functions but as literal strings.

Edit:

Taking a cue out of Dave's answer, figured out a way:

first a little bit of scrubbing:

```<code>for (var handler in this.handlers) {
   if(window[this.handlers[handler]])
        this.handlers[handler] = window[this.handlers[handler]];
};
</code>```

and then call jQuery bind normally

```<code> $elem.bind(this.handlers);
</code>```

Accepting Dave's answer as that is closest.

答:
As someone else mentioned, that wouldn't be valid JSON anyway (which precludes you from using JSON.parse(), among other potential drawbacks).

If your event handler functions are defined in the global window scope, you could call them like this:

```<code>// This is equivalent to defining window.clickEventHandler or
//  window['clickEventHandler'] as a function variable.
function clickEventHander() {
  // Magic.
}

// Valid JSON, using strings to reference the handler's name.
var json = '{"onClickHandler": "clickEventHandler"}'

// You might be using eval() or a framework for this currently.
var handlerMappings = JSON.parse(json);

window[handlerMappings.onClickHandler]();
</code>```

Title: Serialize as object using json.net

Body:
I want certain properties to be serialized as 'objects' and not strings. E.g.

{"onClickHandler": OnClickHandler,
  "onMouseOut": OnMouseOutHandler}

The class def is like this:

public class handlers {

    public string OnClickHandler;
    public string OnMouseOutHandler;

}

Currently it comes out as:

handlers: {"onClickHandler": "OnClickHandler",
  "onMouseOut": "OnMouseOutHandler"}

As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. By emitting them within quotes, they are not interpreted as functions but as literal strings.

Edit:

Taking a cue out of Dave's answer, figured out a way:

first a little bit of scrubbing:

for (var handler in this.handlers) {
   if(window[this.handlers[handler]])
        this.handlers[handler] = window[this.handlers[handler]];
};

and then call jQuery bind normally

 $elem.bind(this.handlers);

Accepting Dave's answer as that is closest.

Body:
As someone else mentioned, that wouldn't be valid JSON anyway (which precludes you from using JSON.parse(), among other potential drawbacks).

If your event handler functions are defined in the global window scope, you could call them like this:

// This is equivalent to defining window.clickEventHandler or
//  window['clickEventHandler'] as a function variable.
function clickEventHander() {
  // Magic.
}

// Valid JSON, using strings to reference the handler's name.
var json = '{"onClickHandler": "clickEventHandler"}'

// You might be using eval() or a framework for this currently.
var handlerMappings = JSON.parse(json);

window[handlerMappings.onClickHandler]();


问:
How to specify python3 kernel in jupyter in pyCharm?
Here is my setting

and this is my script

I am trying to use jupyter notebook in pyCharm, but it kept using python2 instead of python3.

Any idea about this problem?

Add:

this pic is running jupyter notebook in chrome.

答:
When you kick off Jupyter-notebook from within PyCharm there is a configuration which is created. If the configuration is initially 2.7 ( I think it defaults to the current interpreter), and then keep using that same configuration, it wouldn't matter the state of the current project interpreter because it would be using the value saved in the run configuration.

You can modify your run configuration by

Run | Run...

Edit Configurations...

Select your Jupyter Notebook run configuration on the left (here is untitled4)

Make sure the python interpreter is correct here on the right

I was able to start a jupyter notebook like this and get it to output python 3 by doing this. Hope this is what you are needing.


问:
spark join function error
I have a big dataframe and I want to join it with a small csv file.
So I broadcast my small file:

```<code>val rdd = sc.textFile("hdfs:///user/zed/file/app_desc")
val id_dec = sc.broadcast(rdd.map(line=>(line.split(";")(0),line.split(";")(1))).collectAsMap)
</code>```

and I make a function to get the id (input) and return the description

```<code>def extract_connection_type(input:Integer): String = {
  if (input == null || input.length() == 0)
    input;
  else try {
    id_dec.value.get(input)
  } catch {
     case e: Exception => throw new IOException("UDF:Caught exception processing input row :" + input + e.toString);
  }
}
</code>```

Afterwards, when I create my schema I use this function to make my join

```<code>def structure(line: String): structure_Ot = {
  val fields = line.split("\\\t",-1);
  val Name1 = fields(0);
  val Name2 = fields(1);
  val Appd = fields(2).toInt;
  val App = extract_connection_type(Appd);
  val ot_str = new structure_Ot(Name1, Name2, App)
  ot_str
}
</code>```

but I get this error:

```<code><console>:93: error: type mismatch;
 found   : String
 required: Int
</code>```

and even when I change my input to Integer; my error change to:

```<code>found   : String
required: Int
</code>```

What is the reason of this error?

答:
There's a lot of type mismatches in your code, you'll need to fix them all:

id_dec has the type Broadcast[Map[String, String]] (because you create an RDD[(String, String)] and then call collectAsMap and broadcast on the result); In your extract_connection_type, you call id_dec.value.get(input) where input has type Int, and the map's key is a String. You can fix that either by changing the type of input to String, or by changing id_dec into a Broadcast[Map[Int, String]] by collecting and broadcasting an RDD[(Int, String)] in the first place; If you choose the former, you'll have to adjust your structure function too, so it passes a String and not an Int.

Another issue in using id_dec.value.get(input) is that get returns an Option[V] (where V is the type of the map's values) and not a V. You can use the apply method (implicitly) instead: id_dec.value(input), which will return a String or throw an exception if no matching key found

Altogether, this is a compiling version of your code:

```<code>val rdd = sc.textFile("hdfs:///user/zed/file/app_desc")
val id_dec: Broadcast[Map[String, String]] = sc.broadcast(rdd.map(line=>(line.split(";")(0),line.split(";")(1))).collectAsMap)

def extract_connection_type(input: String): String = {
  if (input == null || input.length() == 0)
    input
  else try {
    id_dec.value(input)
  } catch {
    case e: Exception => throw new IOException("UDF:Caught exception processing input row :" + input + e.toString);
  }
}

def structure(line: String): structure_Ot = {
  val fields = line.split("\\\t",-1)
  val Name1 = fields(0)
  val Name2 = fields(1)
  val Appd = fields(2)
  val App = extract_connection_type(Appd)
  val ot_str = structure_Ot(Name1, Name2, App.toInt)
  ot_str
}
</code>```

A good way to resolve these issues yourself is to explicitly type each value you define; That way you'll see where the error is more clearly - if you expect id_dec to have a certain type, the error will point to its assignment if there's an issue where the wrong type is assigned.

Title: spark join function error

Body:
I have a big dataframe and I want to join it with a small csv file.
So I broadcast my small file:

val rdd = sc.textFile("hdfs:///user/zed/file/app_desc")
val id_dec = sc.broadcast(rdd.map(line=>(line.split(";")(0),line.split(";")(1))).collectAsMap)

and I make a function to get the id (input) and return the description

def extract_connection_type(input:Integer): String = {
  if (input == null || input.length() == 0)
    input;
  else try {
    id_dec.value.get(input)
  } catch {
     case e: Exception => throw new IOException("UDF:Caught exception processing input row :" + input + e.toString);
  }
}

Afterwards, when I create my schema I use this function to make my join

def structure(line: String): structure_Ot = {
  val fields = line.split("\\\t",-1);
  val Name1 = fields(0);
  val Name2 = fields(1);
  val Appd = fields(2).toInt;
  val App = extract_connection_type(Appd);
  val ot_str = new structure_Ot(Name1, Name2, App)
  ot_str
}

but I get this error:

<console>:93: error: type mismatch;
 found   : String
 required: Int

and even when I change my input to Integer; my error change to:

found   : String
required: Int

What is the reason of this error?

Body:
There's a lot of type mismatches in your code, you'll need to fix them all:

id_dec has the type Broadcast[Map[String, String]] (because you create an RDD[(String, String)] and then call collectAsMap and broadcast on the result); In your extract_connection_type, you call id_dec.value.get(input) where input has type Int, and the map's key is a String. You can fix that either by changing the type of input to String, or by changing id_dec into a Broadcast[Map[Int, String]] by collecting and broadcasting an RDD[(Int, String)] in the first place; If you choose the former, you'll have to adjust your structure function too, so it passes a String and not an Int.

Another issue in using id_dec.value.get(input) is that get returns an Option[V] (where V is the type of the map's values) and not a V. You can use the apply method (implicitly) instead: id_dec.value(input), which will return a String or throw an exception if no matching key found

Altogether, this is a compiling version of your code:

val rdd = sc.textFile("hdfs:///user/zed/file/app_desc")
val id_dec: Broadcast[Map[String, String]] = sc.broadcast(rdd.map(line=>(line.split(";")(0),line.split(";")(1))).collectAsMap)

def extract_connection_type(input: String): String = {
  if (input == null || input.length() == 0)
    input
  else try {
    id_dec.value(input)
  } catch {
    case e: Exception => throw new IOException("UDF:Caught exception processing input row :" + input + e.toString);
  }
}

def structure(line: String): structure_Ot = {
  val fields = line.split("\\\t",-1)
  val Name1 = fields(0)
  val Name2 = fields(1)
  val Appd = fields(2)
  val App = extract_connection_type(Appd)
  val ot_str = structure_Ot(Name1, Name2, App.toInt)
  ot_str
}

A good way to resolve these issues yourself is to explicitly type each value you define; That way you'll see where the error is more clearly - if you expect id_dec to have a certain type, the error will point to its assignment if there's an issue where the wrong type is assigned.


问:
Error : app-scripts serve unexpectedly failed.settings in ionic3
I just encountered this error while running the command ionic serve on my ionic 3 project.

```<code>[ERROR] app-scripts serve unexpectedly failed.settings: undefinedcontext: [object Object]
</code>```

I need a quick fix cos my app failed to build.

答: you should rename you project-folder's name, run ionic serve then rename it back and run ionic serve again. I don't know why it work, maybe the cache of apache server was saving some temporary data that can't delete because it defined that the project is still running (just my opinion).

Body:
I just encountered this error while running the command ionic serve on my ionic 3 project.

[ERROR] app-scripts serve unexpectedly failed.settings: undefinedcontext: [object Object]

I need a quick fix cos my app failed to build.


问:
Parse error in response of AJAX call
I am new to javascript and jquery, in my code I'm initiating a AJAX call and I get the following response.

I'm trying to implement an autocomplete functionality. I am using below code to do AJAX call.

```<code>$( "#city" ).autocomplete({
      source: function( request, response ) {
        jQuery.ajax({
          url: "the url",
          data: {SearchTerm: request.term}
          success: function (data) {
               console.log("the data is" +data);
               response(data);
            }
        }).fail(function (jqXHR, textStatus, error) {
             console.log("failure1" + textStatus);
             console.log("failure2" + jqXHR.status);
    });
      },
      minLength: 3,
      select: function( event, ui ) {
        console.log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
  });
</code>```

Even though I see 200 response from the server and the response in JSON format, success method doesn't get called and fail get called. Since I'm getting JSON response with 200 status, doesn't success method should get called?

答:
Try this, may be this will help you :

Option 1 :

May be you accidently turning On Magic Quotes in PHP

But this function is already deprecated in PHP 5.3.0.

And REMOVED as of PHP 5.4.0. as mentioned in here

Go to your php.ini file

Search this keyword : magic_quotes_gpc

Set it to OFF : magic_quotes_gpc = Off

Option 2 :

Do it on your code like this :

```<code>if (get_magic_quotes_gpc()) {
    $returnedValue = stripslashes($yourReturnedValue);
}
</code>```

Title: Parse error in response of AJAX call

Body:
I am new to javascript and jquery, in my code I'm initiating a AJAX call and I get the following response.

I'm trying to implement an autocomplete functionality. I am using below code to do AJAX call.

$( "#city" ).autocomplete({
      source: function( request, response ) {
        jQuery.ajax({
          url: "the url",
          data: {SearchTerm: request.term}
          success: function (data) {
               console.log("the data is" +data);
               response(data);
            }
        }).fail(function (jqXHR, textStatus, error) {
             console.log("failure1" + textStatus);
             console.log("failure2" + jqXHR.status);
    });
      },
      minLength: 3,
      select: function( event, ui ) {
        console.log( ui.item ?
          "Selected: " + ui.item.label :
          "Nothing selected, input was " + this.value);
      },
      open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
      },
      close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
      }
    });
  });

Even though I see 200 response from the server and the response in JSON format, success method doesn't get called and fail get called. Since I'm getting JSON response with 200 status, doesn't success method should get called?

Body:
Try this, may be this will help you :

Option 1 :

May be you accidently turning On Magic Quotes in PHP

But this function is already deprecated in PHP 5.3.0.

And REMOVED as of PHP 5.4.0. as mentioned in here

Go to your php.ini file

Search this keyword : magic_quotes_gpc

Set it to OFF : magic_quotes_gpc = Off

Option 2 :

Do it on your code like this :

if (get_magic_quotes_gpc()) {
    $returnedValue = stripslashes($yourReturnedValue);
}


问:
Faster alternative to push_back(size is known)
I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?

答:
You could use a custom allocator which avoids default initialisation of all elements, as discussed in this answer, in conjunction with ordinary element access:

```<code>const size_t N = 172490752;
std::vector<float, uninitialised_allocator<float> > vec(N);
for(size_t i=0; i!=N; ++i)
    vec[i] = the_value_for(i);
</code>```

This avoids (i) default initializing all elements, (ii) checking for capacity at every push, and (iii) reallocation, but at the same time preserves all the convenience of using std::vector (rather than std::unique_ptr<float[]>). However, the allocator template parameter is unusual, so you will need to use generic code rather than std::vector-specific code.

Body:
You could use a custom allocator which avoids default initialisation of all elements, as discussed in this answer, in conjunction with ordinary element access:

const size_t N = 172490752;
std::vector<float, uninitialised_allocator<float> > vec(N);
for(size_t i=0; i!=N; ++i)
    vec[i] = the_value_for(i);

This avoids (i) default initializing all elements, (ii) checking for capacity at every push, and (iii) reallocation, but at the same time preserves all the convenience of using std::vector (rather than std::unique_ptr<float[]>). However, the allocator template parameter is unusual, so you will need to use generic code rather than std::vector-specific code.


问:
SweetAlert Calling code after clicking "Cancel" button
I have written following code, I want to call a code under "Cancel" button:

```<code>vm.saveGroup = function(){
    SweetAlert.swal({
        title: "Name this Device Group",
        text: "Please provide a name that you want your device group to be saved under. Also, make sure that you already specified all needed filters before you save the list.",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        inputPlaceholder: "Device Group name"
    },
    function(inputValue){
        if (inputValue === false) {
            return false;
        }
        if (inputValue === "") {
            /*eslint-disable */
            swal.showInputError("You need to write something!");
            /*eslint-enable */
            return false;
        }

        deviceGroupsFactory.saveGroup(inputValue, vm.filterOutput)
            .then(function(response){
                if (response.status == 200){
                    SweetAlert.swal("Device Group saved!", "You should now see your device group on the list.", "success");
                    $state.go('main.template.devices.groups');
                }
                else {

                    SweetAlert.swal("Error!", response.statusText, "error");

                  console.log('xxx');
                }
            });
    });

}
</code>```

but I cannot call "cancel clicked". I was looking for in docs but cannot find the solution.

答:
You're passing too many parameters to the swal constructor. It needs only two:

swal(options, callback)

options: Attributes to design the alert

callback: The callback function to manage the events

When you use a simple confirm, the callback receive only one parameter that indicates the user choice:

true: Confirm

false: Cancel

With inputbox you will receive the user's input string as parameter.

When you merge together inputbox and confirm, you could receive:

the input string value: When the user press Confirm

false: When user press Cancel

So, you have to use the Strict Equality Comparison in order to know if user pressed cancel or have inserted the string false in the input box.

Please see the following simple example:

swal({
  title: "Are you sure?",
  text: "Press CANCEL, please!",
  type: "input",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "CONFIRM",
  cancelButtonText: "CANCEL",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(inputValue){
  //Use the "Strict Equality Comparison" to accept the user's input "false" as string)
  if (inputValue===false) {
    swal("Well done!");
    console.log("Do here everything you want");
  } else {
    swal("Oh no...","press CANCEL please!");
    console.log("The user says: ", inputValue);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js"></script></code>```

I hope it helps you, bye.

Body:
I have written following code, I want to call a code under "Cancel" button:

vm.saveGroup = function(){
    SweetAlert.swal({
        title: "Name this Device Group",
        text: "Please provide a name that you want your device group to be saved under. Also, make sure that you already specified all needed filters before you save the list.",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        inputPlaceholder: "Device Group name"
    },
    function(inputValue){
        if (inputValue === false) {
            return false;
        }
        if (inputValue === "") {
            /*eslint-disable */
            swal.showInputError("You need to write something!");
            /*eslint-enable */
            return false;
        }

        deviceGroupsFactory.saveGroup(inputValue, vm.filterOutput)
            .then(function(response){
                if (response.status == 200){
                    SweetAlert.swal("Device Group saved!", "You should now see your device group on the list.", "success");
                    $state.go('main.template.devices.groups');
                }
                else {

                    SweetAlert.swal("Error!", response.statusText, "error");

                  console.log('xxx');
                }
            });
    });

}

but I cannot call "cancel clicked". I was looking for in docs but cannot find the solution.

Body:
You're passing too many parameters to the swal constructor. It needs only two:

swal(options, callback)

options: Attributes to design the alert

callback: The callback function to manage the events

When you use a simple confirm, the callback receive only one parameter that indicates the user choice:

true: Confirm

false: Cancel

With inputbox you will receive the user's input string as parameter.

When you merge together inputbox and confirm, you could receive:

the input string value: When the user press Confirm

false: When user press Cancel

So, you have to use the Strict Equality Comparison in order to know if user pressed cancel or have inserted the string false in the input box.

Please see the following simple example:

swal({
  title: "Are you sure?",
  text: "Press CANCEL, please!",
  type: "input",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "CONFIRM",
  cancelButtonText: "CANCEL",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(inputValue){
  //Use the "Strict Equality Comparison" to accept the user's input "false" as string)
  if (inputValue===false) {
    swal("Well done!");
    console.log("Do here everything you want");
  } else {
    swal("Oh no...","press CANCEL please!");
    console.log("The user says: ", inputValue);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js"></script>

I hope it helps you, bye.

ContentLicense: CC BY-SA 4.0


问:
Oracle 'Partition By' and 'Row_Number' keyword along with pivot
I have this query written by someone else and I am trying to figure out how is it working. I have general idea about all these things such as row_number() , partition by, pivot but I am unable to understand them all together.

For this query :

```<code>select
    d, p, s, a
from
(
    select name,occupation, (ROW_NUMBER() OVER (partition by occupation order by name)) as rownumber from occupations
)
pivot
(
    max(name)
    for occupation
    in ('Doctor' as d, 'Professor' as p, 'Singer' as s, 'Actor' as a)
)
order by rownumber;
</code>```

This is the input table on which the above query works :

This it the output generated by the query which is correct as per the question :

```<code>Jenny    Ashley     Meera  Jane
Samantha Christeen  Priya  Julia
NULL     Ketty      NULL   Maria
</code>```

Now, I want to know how the output is generated by the query i.e. step by step with flow of execution. Explanation with easy examples matching the above situation would be much appreciated. Thanks in advance.

答:
After from clause you have following :

select name,occupation, (ROW_NUMBER() OVER (partition by occupation order by name))

Above virtually restack your table data in three columns - Name, occupation, rownumber. rownumber will reset itself as soon as occupation column changes. Output data will be like :

```<code>NAME                 OCCUPATION            ROWNUMBER
-------------------- -------------------- ----------
Jane                 ACTOR                1
Julia                ACTOR                2
Maria                ACTOR                3
JENNY                DOCTOR               1 <-- rownumber reset to 1
Sammantha            DOCTOR               2
</code>```

Pivot function let you aggregate result & rotate rows into columns.
Pivot usage code is :

```<code>PIVOT
(
  aggregate_function(column2)
  FOR column2
  IN ( expr1, expr2, ... expr_n) | subquery
)
</code>```

So your PIVOT function have name stacked NAME based on OCCUPATION . Each stack (column in output) is ordered by rownumber column inserted via first subquery.

Body:
I have this query written by someone else and I am trying to figure out how is it working. I have general idea about all these things such as row_number() , partition by, pivot but I am unable to understand them all together.

For this query :

select
    d, p, s, a
from
(
    select name,occupation, (ROW_NUMBER() OVER (partition by occupation order by name)) as rownumber from occupations
)
pivot
(
    max(name)
    for occupation
    in ('Doctor' as d, 'Professor' as p, 'Singer' as s, 'Actor' as a)
)
order by rownumber;

This is the input table on which the above query works :

This it the output generated by the query which is correct as per the question :

Jenny    Ashley     Meera  Jane
Samantha Christeen  Priya  Julia
NULL     Ketty      NULL   Maria

Now, I want to know how the output is generated by the query i.e. step by step with flow of execution. Explanation with easy examples matching the above situation would be much appreciated. Thanks in advance.

Body:
After from clause you have following :

select name,occupation, (ROW_NUMBER() OVER (partition by occupation order by name))

Above virtually restack your table data in three columns - Name, occupation, rownumber. rownumber will reset itself as soon as occupation column changes. Output data will be like :

NAME                 OCCUPATION            ROWNUMBER
-------------------- -------------------- ----------
Jane                 ACTOR                1
Julia                ACTOR                2
Maria                ACTOR                3
JENNY                DOCTOR               1 <-- rownumber reset to 1
Sammantha            DOCTOR               2

Pivot function let you aggregate result & rotate rows into columns.
Pivot usage code is :

PIVOT
(
  aggregate_function(column2)
  FOR column2
  IN ( expr1, expr2, ... expr_n) | subquery
)

So your PIVOT function have name stacked NAME based on OCCUPATION . Each stack (column in output) is ordered by rownumber column inserted via first subquery.


问:
Get Multiple rows from multiple values (columns) in SQL Server 2008 R2
I have this table

```<code>+-----+------+--------+--------+
| ID  | Name |  Start |   End  |
+-----+------+--------+--------+
| 20  | Mike |   1    |    3   |
| 21  | Luke |   4    |    7   |
+-----+------+--------+--------+
</code>```

And I want to generate all rows based on the range (start / end) of each person.

The outcome should be this

```<code>+-----+------+-----------------+
| ID  | Name |    Start_End    |
+-----+------+-----------------+
| 20  | Mike |        1        |
| 20  | Mike |        2        |
| 20  | Mike |        3        |
| 21  | Luke |        4        |
| 21  | Luke |        5        |
| 21  | Luke |        6        |
| 21  | Luke |        7        |
+-----+------+--------+--------+
</code>```

To get unique values based on Start and End column, I have this function

```<code>CREATE FUNCTION [dbo].[ufn_SplitRange] (@Start INT, @End INT)
RETURNS TABLE
AS
RETURN
(
    SELECT  TOP (@End - @Start+1) ROW_NUMBER() OVER (ORDER BY S.[object_id])+(@Start - 1) [Start_End]
    FROM    sys.all_objects S WITH (NOLOCK)
);
</code>```

The above function returns the output of (based on Mike range of 1-3):

```<code>1
2
3
</code>```

I have been trying several approaches and, I can't find the right solution, it seems a very common task, but a tricky one.

Any input is highly appreciated

Body:
I have this table

+-----+------+--------+--------+
| ID  | Name |  Start |   End  |
+-----+------+--------+--------+
| 20  | Mike |   1    |    3   |
| 21  | Luke |   4    |    7   |
+-----+------+--------+--------+

And I want to generate all rows based on the range (start / end) of each person.

The outcome should be this

+-----+------+-----------------+
| ID  | Name |    Start_End    |
+-----+------+-----------------+
| 20  | Mike |        1        |
| 20  | Mike |        2        |
| 20  | Mike |        3        |
| 21  | Luke |        4        |
| 21  | Luke |        5        |
| 21  | Luke |        6        |
| 21  | Luke |        7        |
+-----+------+--------+--------+

To get unique values based on Start and End column, I have this function

CREATE FUNCTION [dbo].[ufn_SplitRange] (@Start INT, @End INT)
RETURNS TABLE
AS
RETURN
(
    SELECT  TOP (@End - @Start+1) ROW_NUMBER() OVER (ORDER BY S.[object_id])+(@Start - 1) [Start_End]
    FROM    sys.all_objects S WITH (NOLOCK)
);

The above function returns the output of (based on Mike range of 1-3):

1
2
3

I have been trying several approaches and, I can't find the right solution, it seems a very common task, but a tricky one.

Any input is highly appreciated

Body:
using cross apply():

select t.Id, t.Name, x.Start_End
from t
  cross apply dbo.ufn_SplitRange(t.Start,t.[End]) as x

rextester demo: http://rextester.com/FVA48693

returns:

+----+------+-----------+
| Id | Name | Start_End |
+----+------+-----------+
| 20 | Mike |         1 |
| 20 | Mike |         2 |
| 20 | Mike |         3 |
| 21 | Luke |         4 |
| 21 | Luke |         5 |
| 21 | Luke |         6 |
| 21 | Luke |         7 |
+----+------+-----------+


问:
Why is Long.valueOf(0).equals(Integer.valueOf(0)) false?
This questions is prompted by strange HashMap.put() behaviour

I think I understand why Map<K,V>.put takes a K but Map<K,V>.get takes an Object, it seems not doing so will break too much existing code.

Now we get into a very error-prone scenario:

```<code>java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(5L,"Five"); // compiler barfs on m.put(5, "Five")
m.contains(5); // no complains from compiler, but returns false
</code>```

Couldn't this have been solved by returning true if the Long value was withing int range and the values are equal?

答:
So you code should be....

```<code>java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(5L, "Five"); // compiler barfs on m.put(5, "Five")
System.out.println(m.containsKey(5L)); // true
</code>```

You are forgetting that java is autoboxing your code, so the above code would be equivelenet to

```<code>java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(new Long(5L), "Five"); // compiler barfs on m.put(5, "Five")
System.out.println(m.containsKey(new Long(5))); // true
System.out.println(m.containsKey(new Long(5L))); // true
</code>```

So a part of your problem is the autoboxing.  The other part is that you have different types as other posters have stated.

OwnerDisplayName: Hemal Pandya

Body:
This questions is prompted by strange HashMap.put() behaviour

I think I understand why Map<K,V>.put takes a K but Map<K,V>.get takes an Object, it seems not doing so will break too much existing code.

Now we get into a very error-prone scenario:

java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(5L,"Five"); // compiler barfs on m.put(5, "Five")
m.contains(5); // no complains from compiler, but returns false

Couldn't this have been solved by returning true if the Long value was withing int range and the values are equal?

Body:
So you code should be....

java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(5L, "Five"); // compiler barfs on m.put(5, "Five")
System.out.println(m.containsKey(5L)); // true

You are forgetting that java is autoboxing your code, so the above code would be equivelenet to

java.util.HashMap<Long, String> m = new java.util.HashMap<Long, String>();
m.put(new Long(5L), "Five"); // compiler barfs on m.put(5, "Five")
System.out.println(m.containsKey(new Long(5))); // true
System.out.println(m.containsKey(new Long(5L))); // true

So a part of your problem is the autoboxing.  The other part is that you have different types as other posters have stated.

OwnerDisplayName: Milhous

LastEditorDisplayName: Milhous


问:
Print JSON data from csv list of multiple urls
Very new to Python and haven't found specific answer on SO but apologies in advance if this appears very naive or elsewhere already.

I am trying to print 'IncorporationDate' JSON data from multiple urls of public data set. I have the urls saved as a csv file, snippet below. I am only getting as far as printing ALL the JSON data from one url, and I am uncertain how to run that over all of the csv urls, and write to csv just the IncorporationDate values.

Any basic guidance or edits are really welcomed!

```<code>try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json

def get_jsonparsed_data(url):

    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url = ("http://data.companieshouse.gov.uk/doc/company/01046514.json")
print(get_jsonparsed_data(url))

import csv
with open('test.csv') as f:
    lis=[line.split() for line in f]
    for i,x in enumerate(lis):
        print ()

import StringIO
s = StringIO.StringIO()
with open('example.csv', 'w') as f:
    for line in s:
        f.write(line)
</code>```

Snippet of csv:

```<code>http://business.data.gov.uk/id/company/01046514.json
http://business.data.gov.uk/id/company/01751318.json
http://business.data.gov.uk/id/company/03164710.json
http://business.data.gov.uk/id/company/04403406.json
http://business.data.gov.uk/id/company/04405987.json
</code>```

答:
Welcome to the Python world.

For dealing with making http requests, we commonly use requests because it's dead simple api.

The code snippet below does what I believe you want:

It grabs the data from each of the urls you posted

It creates a new CSV file with each of the IncorporationDate keys.

```</p>

```import csv
import requests

COMPANY_URLS = [
    'http://business.data.gov.uk/id/company/01046514.json',
    'http://business.data.gov.uk/id/company/01751318.json',
    'http://business.data.gov.uk/id/company/03164710.json',
    'http://business.data.gov.uk/id/company/04403406.json',
    'http://business.data.gov.uk/id/company/04405987.json',
]

def get_company_data():
    for url in COMPANY_URLS:
        res = requests.get(url)
        if res.status_code == 200:
             yield res.json()

if __name__ == '__main__':
    for data in get_company_data():
        try:
            incorporation_date = data['primaryTopic']['IncorporationDate']
        except KeyError:
            continue
        else:
            with open('out.csv', 'a') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([incorporation_date])
```

<p>```

Body:
Very new to Python and haven't found specific answer on SO but apologies in advance if this appears very naive or elsewhere already.

I am trying to print 'IncorporationDate' JSON data from multiple urls of public data set. I have the urls saved as a csv file, snippet below. I am only getting as far as printing ALL the JSON data from one url, and I am uncertain how to run that over all of the csv urls, and write to csv just the IncorporationDate values.

Any basic guidance or edits are really welcomed!

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json

def get_jsonparsed_data(url):

    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url = ("http://data.companieshouse.gov.uk/doc/company/01046514.json")
print(get_jsonparsed_data(url))

import csv
with open('test.csv') as f:
    lis=[line.split() for line in f]
    for i,x in enumerate(lis):
        print ()

import StringIO
s = StringIO.StringIO()
with open('example.csv', 'w') as f:
    for line in s:
        f.write(line)

Snippet of csv:

http://business.data.gov.uk/id/company/01046514.json
http://business.data.gov.uk/id/company/01751318.json
http://business.data.gov.uk/id/company/03164710.json
http://business.data.gov.uk/id/company/04403406.json
http://business.data.gov.uk/id/company/04405987.json

Body:
Welcome to the Python world.

For dealing with making http requests, we commonly use requests because it's dead simple api.

The code snippet below does what I believe you want:

It grabs the data from each of the urls you posted

It creates a new CSV file with each of the IncorporationDate keys.

```</p>

<pre><code>import csv
import requests

COMPANY_URLS = [
    'http://business.data.gov.uk/id/company/01046514.json',
    'http://business.data.gov.uk/id/company/01751318.json',
    'http://business.data.gov.uk/id/company/03164710.json',
    'http://business.data.gov.uk/id/company/04403406.json',
    'http://business.data.gov.uk/id/company/04405987.json',
]

def get_company_data():
    for url in COMPANY_URLS:
        res = requests.get(url)
        if res.status_code == 200:
             yield res.json()

if __name__ == '__main__':
    for data in get_company_data():
        try:
            incorporation_date = data['primaryTopic']['IncorporationDate']
        except KeyError:
            continue
        else:
            with open('out.csv', 'a') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow([incorporation_date])
</code></pre>

<p>```


答:
You can use tally table as below:

```<code>Select Id, Name, Start_end from #Values
cross apply (
        Select top ([end] - [start] +1) Start_end = [start] + Row_number() over (order by (Select NULL))-1
        from master..spt_values s1, master..spt_values s2
        ) a
</code>```

Output :

```<code>+----+------+----+
| Id | Name | RN |
+----+------+----+
| 20 | Mike |  1 |
| 20 | Mike |  2 |
| 20 | Mike |  3 |
| 21 | Luke |  4 |
| 21 | Luke |  5 |
| 21 | Luke |  6 |
| 21 | Luke |  7 |
+----+------+----+
</code>```

Title: Get Multiple rows from multiple values (columns) in SQL Server 2008 R2

Body:
You can use tally table as below:

Select Id, Name, Start_end from #Values
cross apply (
        Select top ([end] - [start] +1) Start_end = [start] + Row_number() over (order by (Select NULL))-1
        from master..spt_values s1, master..spt_values s2
        ) a

Output :

+----+------+----+
| Id | Name | RN |
+----+------+----+
| 20 | Mike |  1 |
| 20 | Mike |  2 |
| 20 | Mike |  3 |
| 21 | Luke |  4 |
| 21 | Luke |  5 |
| 21 | Luke |  6 |
| 21 | Luke |  7 |
+----+------+----+


问:
localToGlobal not working - for reals though
I know there a bajillion threads on this topic, and maybe I am retarded, but this simply isn't working and I think I am missing something really key?

Lets say I have sprites _testTarget and _testParent nested like this.

```<code>_testParent = new Sprite();
this.addChild(_testParent);

_testTarget = new Sprite()
_testParent.addChild(_testParent);
</code>```

And lets say I want to get the global cords of _testTarget.  When I do localToGlobal I always get back 0,0 when I know for a fact its actual cords are like 200,100

```<code>var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.localToGlobal(point);  // returns 0,0

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.parent.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.parent.localToGlobal(point);  // Breaks, "parent" is null
</code>```

If it helps, this class/sprite instantiated inside of a sprite, inside of a sprite, inside of a sprite...etc and the reason its cords are 200,100 are because one of its parent containers is set to that - but I thought localToGlobal was supposed to go all the way to very top layer?  Help?

答:
You must have a problem somewhere else (I can't see anyone in the code you pasted, except for the one mentioned by TandemAdam).

This works as expected:

```<code>var _testParent:Sprite;
var _testTarget:Sprite;
var _yetAnotherParent:Sprite;

_yetAnotherParent = new Sprite();
this.addChild(_yetAnotherParent);

_testParent = new Sprite();
_yetAnotherParent.addChild(_testParent);

_testTarget = new Sprite()
_testParent.addChild(_testTarget);

_testParent.y = 100;
_yetAnotherParent.y = -500;

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.parent.localToGlobal(point);

trace(point); // (x=0, y=-400)
</code>```

As a rule of thumb, when translating between coordinate spaces, the object on which you want to call localToGlobal or globalToLocal is almost always the parent of the object you're interested in, because an object's x and y are offsets relative to its parent.

Body:
I know there a bajillion threads on this topic, and maybe I am retarded, but this simply isn't working and I think I am missing something really key?

Lets say I have sprites _testTarget and _testParent nested like this.

_testParent = new Sprite();
this.addChild(_testParent);

_testTarget = new Sprite()
_testParent.addChild(_testParent);

And lets say I want to get the global cords of _testTarget.  When I do localToGlobal I always get back 0,0 when I know for a fact its actual cords are like 200,100

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.localToGlobal(point);  // returns 0,0

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.parent.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.localToGlobal(point);  // returns 0,0

var point:Point = new Point(this.x, this.y);
    point = this.parent.localToGlobal(point);  // Breaks, "parent" is null

If it helps, this class/sprite instantiated inside of a sprite, inside of a sprite, inside of a sprite...etc and the reason its cords are 200,100 are because one of its parent containers is set to that - but I thought localToGlobal was supposed to go all the way to very top layer?  Help?

Body:
You must have a problem somewhere else (I can't see anyone in the code you pasted, except for the one mentioned by TandemAdam).

This works as expected:

var _testParent:Sprite;
var _testTarget:Sprite;
var _yetAnotherParent:Sprite;

_yetAnotherParent = new Sprite();
this.addChild(_yetAnotherParent);

_testParent = new Sprite();
_yetAnotherParent.addChild(_testParent);

_testTarget = new Sprite()
_testParent.addChild(_testTarget);

_testParent.y = 100;
_yetAnotherParent.y = -500;

var point:Point = new Point(_testTarget.x, _testTarget.y);
    point = _testTarget.parent.localToGlobal(point);

trace(point); // (x=0, y=-400)

As a rule of thumb, when translating between coordinate spaces, the object on which you want to call localToGlobal or globalToLocal is almost always the parent of the object you're interested in, because an object's x and y are offsets relative to its parent.


问:
Remove everything between tag Regex
I m trying to remove everything inside any html tag:

input:

```<code><a class="yoyo"> <h1 id="test"> hello </h1> </a>
</code>```

weird example but well

output:

```<code><a><h1>hello</h1></a>
</code>```

I ve tried /(<\w)(?:.*)(>)/gmi but its not working...

If you have any clue on that .
Thanks

So to explain it more after your comment I scrapped a website and I have a .txt file that i wanna clean. It will contain the whole html of a page and i want to clean every single html tag and remove the spaces aswell.
So everything between any <* and > should be removed.

答:
How about the following regex:

```<code><[^>]*>
</code>```

You will have to concatenate all the matches.

Title: Remove everything between tag Regex

Body:
I m trying to remove everything inside any html tag:

input:

 hello

weird example but well

output:

hello

I ve tried /(<\w)(?:.*)(>)/gmi but its not working...

If you have any clue on that .
Thanks

So to explain it more after your comment I scrapped a website and I have a .txt file that i wanna clean. It will contain the whole html of a page and i want to clean every single html tag and remove the spaces aswell.
So everything between any <* and > should be removed.

Body:
How about the following regex:

<[^>]*>

You will have to concatenate all the matches.


问:
BlockingDataflowPipelineRunner runner category not available
I'm new to Google dataflow, and I'm following the QuickStart guide from
here to build the sample wordcount project in Eclipse.

However, when I setup the "New Launch Configuration", there is no option "BlockingDataflowPipelineRunner" available as shown from the attached screen shot.  Only "DirectPipelineRunner" and "DataflowPipelineRunner" are available.

Can anyone help?

答:
The BlockingDataflowPipelineRunner and DataflowPipelineRunner have been merged. You should be able to use the DataflowRunner.

The blocking behavior is now available within code by calling waitUntilFinish within the code, which the examples should do.


问:
How to change protocol of schemaLocation in Metro web service
I have a web service deployed behind firewall.
Connection between firewall and WS is on 8080 port, but firewall accept requests from outside only on 443 port.

The problem is that when I open wsdl from outside, schemaLocation attribute has wrong value - begins with http://host:8080, but not with https://host:443

I can change port as described here:
http://metro.java.net/2.0/guide/HTTP_address_in_soap_address_and_import_locations.html
but it lead to wrong: http://host:443

Does anyone know how to fix protocol of schemaLocation attribute from http to https?

答: it is here: new location of metro user guide</p>


问:
Adding each element in an array by each element in the same array in python
I need to add each element in an array by each element in the same array and then add the results to a new array. I have tried

```<code>my_list = []

for filename in [my_file]:
    with open(filename) as f:
        my_list += [int(i) for line in f for i in line.split()]

answer = []

for elem in my_list:
    answer += [elem + elem]

print answer
</code>```

When my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], the program prints [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] which is incorrect. How can I fix this?

Body:
I need to add each element in an array by each element in the same array and then add the results to a new array. I have tried

my_list = []

for filename in [my_file]:
    with open(filename) as f:
        my_list += [int(i) for line in f for i in line.split()]

answer = []

for elem in my_list:
    answer += [elem + elem]

print answer

When my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], the program prints [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] which is incorrect. How can I fix this?

Body:
You can try this:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

answer = [i+a for i in my_list for a in my_list]

Output:

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


问:
Prevent uitableview from scrolling after removing last cell
I have a tableview (style - grouped) which contains more rows than can fit into its frame so you have to scroll to see the last row. When I delete the last row the tableview scrolls its content down so the new last row is at the bottom of the frame (kind of fill the empty space).

How can I prevent a UITableView from scrolling after I delete the last row in it? I want it to keep the empty space and do not scroll automatically.

I have tried to set content insets but it doesn't seem to prevent scrolling unfortunately.

EDIT: My code for removing the row:

```<code>func removeLastRow() {
    let indexPath = IndexPath.init(row: self.messages.count - 1, section: 0)

    self.messages.removeLast()
    CATransaction.begin()
    self.tableView.beginUpdates()
    CATransaction.setCompletionBlock { () -> Void in
       // do stuff, add new rows
    }
    self.tableView.deleteRows(at: [indexPath], with: .left)
    self.tableView.endUpdates()
    CATransaction.commit()
}
</code>```

答:
Retreive the cells size before deleting by calling tableView:heightForRowAt: and after deleting, set the vertical content offset of your table view manually to the current vertical content offset, plus the height of the cell.

```<code>let deletedCellHeight = tableView.heightForRowAt(indexPath)
</code>```

Then:

```<code>tableView.contentOffset.x += deletedCellHeight
</code>```

Body:
I have a tableview (style - grouped) which contains more rows than can fit into its frame so you have to scroll to see the last row. When I delete the last row the tableview scrolls its content down so the new last row is at the bottom of the frame (kind of fill the empty space).

How can I prevent a UITableView from scrolling after I delete the last row in it? I want it to keep the empty space and do not scroll automatically.

I have tried to set content insets but it doesn't seem to prevent scrolling unfortunately.

EDIT: My code for removing the row:

func removeLastRow() {
    let indexPath = IndexPath.init(row: self.messages.count - 1, section: 0)

    self.messages.removeLast()
    CATransaction.begin()
    self.tableView.beginUpdates()
    CATransaction.setCompletionBlock { () -> Void in
       // do stuff, add new rows
    }
    self.tableView.deleteRows(at: [indexPath], with: .left)
    self.tableView.endUpdates()
    CATransaction.commit()
}

Body:
Retreive the cells size before deleting by calling tableView:heightForRowAt: and after deleting, set the vertical content offset of your table view manually to the current vertical content offset, plus the height of the cell.

let deletedCellHeight = tableView.heightForRowAt(indexPath)

Then:

tableView.contentOffset.x += deletedCellHeight


问:
a regex to parse BEM class selector with javascript
here my problem :

I want to split a string into an array of object.
My string is a BEM class selector like so :

where my string (without dot) would be splitted by matching '__' and '--'.

foo-bar--baz__foo--bar = ['foo-bar', '--baz', '__foo', '--bar']

foo-bar--baz = ['foo-bar', '--baz']

foo-bar__bar--baz = ['foo-bar', '__bar', '--baz']

foo = ['foo']

I tried with the following regex :

```<code>const regex = /([a-zA-Z0-9']+)(--[a-zA-Z0-9']+)(__[a-zA-Z0-9']+)/g;

while (match = reg.exec(string)) {
    var group1 = match[1];
    var group2 = match[2];
    var group3 = match[3];

    console.log(group1+'; '+group2+'; '+group3);
}
</code>```

but foo-bar--baz__foo--bar only output:

```<code>foo-bar --baz __foo
</code>```

and not the last --bar…

I cannot figure out why.

Also, maybe a better overall solution exist to solve my problem…

Thank's for the help

答: To parse BEM class selector you may use https://github.com/bem-sdk-archive/bem-naming but foo-bar--baz__foo--bar doesn't seem to be a BEM selector ;)

Body:
here my problem :

I want to split a string into an array of object.
My string is a BEM class selector like so :

where my string (without dot) would be splitted by matching '__' and '--'.

foo-bar--baz__foo--bar = ['foo-bar', '--baz', '__foo', '--bar']

foo-bar--baz = ['foo-bar', '--baz']

foo-bar__bar--baz = ['foo-bar', '__bar', '--baz']

foo = ['foo']

I tried with the following regex :

const regex = /([a-zA-Z0-9']+)(--[a-zA-Z0-9']+)(__[a-zA-Z0-9']+)/g;

while (match = reg.exec(string)) {
    var group1 = match[1];
    var group2 = match[2];
    var group3 = match[3];

    console.log(group1+'; '+group2+'; '+group3);
}

but foo-bar--baz__foo--bar only output:

foo-bar --baz __foo

and not the last --bar…

I cannot figure out why.

Also, maybe a better overall solution exist to solve my problem…

Thank's for the help


问:
Implement bookmarking in scorm using javascript
I'm using moodle 3.2 and scorm 1.2
I'm trying to implement bookmark feature in my scorm package containing multiple SCOs.

Here's the code I'm using -

```<code>function SCOonload(){
SCOInitialize();

var bookmark = LMSGetValue("cmi.core.lesson_location");

if (bookmark){
url = bookmark;
}
jumpToPage(url);
}
</code>```

I'm very new to scorm and javascript. What should I write in jumpToPage so that it opens the bookmarked location?

Thanks.

答:
Couple warnings -

If you aren't using AJAX or a iframe/frameset, then JavaScript will initialize on each page which means you have to re-connect the SCORM Runtime API.  You would not want any type of unload event to fire terminating the SCO prematurely.  I have seen cases where the LMS adds extra values to the URL of the SCO Presented and when you change the URL things go sideways (just as a general warning).

LMS's support single page SCO's with their own TOC (Table of Contents) and navigation commonly. And when you get into doing multiple pages within the SCO you get to manage the navigation. So when you bundle multiple pages you'll just need to manage either the IFRAME load of individual pages or a AJAX load of pages.  This has also traditionally been accomplished with other plugin technologies like Flash, Java etc...

Can you just change the page without AJAX and a Frame?  Sure, but I'd caution about how the LMS can behave.  They some times have their own unload listeners and monitor the SCORM Runtime.

Body:
I'm using moodle 3.2 and scorm 1.2
I'm trying to implement bookmark feature in my scorm package containing multiple SCOs.

Here's the code I'm using -

function SCOonload(){
SCOInitialize();

var bookmark = LMSGetValue("cmi.core.lesson_location");

if (bookmark){
url = bookmark;
}
jumpToPage(url);
}

I'm very new to scorm and javascript. What should I write in jumpToPage so that it opens the bookmarked location?

Thanks.