问:
api-platform.com Unable to generate an IRI for the item of type
I'm trying to setup my first api-platform instance and have run into some presumably noob questions around IDE. What I'm trying to do is setting up an register and reset entity in order to deal with registrations and password reminders from an app. And then have the entity's passed to a custom controller to do some checks, balances and mails afterwards (haven’t gotten around to that yet). But I keep running into this error when posting to my custom entities:

```<code>{
    "@context": "/api/contexts/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "Unable to generate an IRI for the item of type \"App\\XXX\\UserBundle\\Entity\\Register\"",
    "trace": [
        {
            "namespace": "",
            "short_class": "",
            "class": "",
            "type": "",
            "function": "",
            "file": "/var/www/webservice/vendor/api-platform/core/src/Bridge/Symfony/Routing/IriConverter.php",
            "line": 116,
            "args": []
        },
        {
            "namespace": "ApiPlatform\\Core\\Bridge\\Symfony\\Routing",
            "short_class": "IriConverter",
            "class": "ApiPlatform\\Core\\Bridge\\Symfony\\Routing\\IriConverter",
            "type": "->",
            "function": "getIriFromItem",
            "file": "/var/www/webservice/vendor/api-platform/core/src/JsonLd/Serializer/ItemNormalizer.php",
            "line": 71,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ]
            ]
        },
        {
            "namespace": "ApiPlatform\\Core\\JsonLd\\Serializer",
            "short_class": "ItemNormalizer",
            "class": "ApiPlatform\\Core\\JsonLd\\Serializer\\ItemNormalizer",
            "type": "->",
            "function": "normalize",
            "file": "/var/www/webservice/vendor/symfony/serializer/Serializer.php",
            "line": 138,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ],
                [
                    "string",
                    "jsonld"
                ],
                [
                    "array",
                    {
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "resource_class": [
                            "string",
                            "App\\XXX\\UserBundle\\Entity\\Register"
                        ],
                        "request_uri": [
                            "string",
                            "/api/register"
                        ],
                        "uri": [
                            "string",
                            "http://webservice.local/api/register"
                        ],
                        "resources": [
                            "object",
                            "ApiPlatform\\Core\\Serializer\\ResourceList"
                        ],
                        "jsonld_has_context": [
                            "boolean",
                            true
                        ]
                    }
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\Serializer",
            "short_class": "Serializer",
            "class": "Symfony\\Component\\Serializer\\Serializer",
            "type": "->",
            "function": "normalize",
            "file": "/var/www/webservice/vendor/symfony/serializer/Serializer.php",
            "line": 111,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ],
                [
                    "string",
                    "jsonld"
                ],
                [
                    "array",
                    {
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "resource_class": [
                            "string",
                            "App\\XXX\\UserBundle\\Entity\\Register"
                        ],
                        "request_uri": [
                            "string",
                            "/api/register"
                        ],
                        "uri": [
                            "string",
                            "http://webservice.local/api/register"
                        ],
                        "resources": [
                            "object",
                            "ApiPlatform\\Core\\Serializer\\ResourceList"
                        ]
                    }
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\Serializer",
            "short_class": "Serializer",
            "class": "Symfony\\Component\\Serializer\\Serializer",
            "type": "->",
            "function": "serialize",
            "file": "/var/www/webservice/vendor/api-platform/core/src/EventListener/SerializeListener.php",
            "line": 67,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ],
                [
                    "string",
                    "jsonld"
                ],
                [
                    "array",
                    {
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "resource_class": [
                            "string",
                            "App\\XXX\\UserBundle\\Entity\\Register"
                        ],
                        "request_uri": [
                            "string",
                            "/api/register"
                        ],
                        "uri": [
                            "string",
                            "http://webservice.local/api/register"
                        ],
                        "resources": [
                            "object",
                            "ApiPlatform\\Core\\Serializer\\ResourceList"
                        ]
                    }
                ]
            ]
        },
        {
            "namespace": "ApiPlatform\\Core\\EventListener",
            "short_class": "SerializeListener",
            "class": "ApiPlatform\\Core\\EventListener\\SerializeListener",
            "type": "->",
            "function": "onKernelView",
            "file": "/var/www/webservice/vendor/symfony/event-dispatcher/EventDispatcher.php",
            "line": 212,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent"
                ],
                [
                    "string",
                    "kernel.view"
                ],
                [
                    "object",
                    "Symfony\\Component\\EventDispatcher\\EventDispatcher"
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\EventDispatcher",
            "short_class": "EventDispatcher",
            "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
            "type": "->",
            "function": "doDispatch",
            "file": "/var/www/webservice/vendor/symfony/event-dispatcher/EventDispatcher.php",
            "line": 44,
            "args": [
                [
                    "array",
                    [
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\Validator\\EventListener\\ValidateListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ],
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\EventListener\\WriteListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ],
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\EventListener\\SerializeListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ],
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\EventListener\\RespondListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ]
                    ]
                ],
                [
                    "string",
                    "kernel.view"
                ],
                [
                    "object",
                    "Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent"
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\EventDispatcher",
            "short_class": "EventDispatcher",
            "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
            "type": "->",
            "function": "dispatch",
            "file": "/var/www/webservice/vendor/symfony/http-kernel/HttpKernel.php",
            "line": 154,
            "args": [
                [
                    "string",
                    "kernel.view"
                ],
                [
                    "object",
                    "Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent"
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\HttpKernel",
            "short_class": "HttpKernel",
            "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
            "type": "->",
            "function": "handleRaw",
            "file": "/var/www/webservice/vendor/symfony/http-kernel/HttpKernel.php",
            "line": 66,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpFoundation\\Request"
                ],
                [
                    "integer",
                    1
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\HttpKernel",
            "short_class": "HttpKernel",
            "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
            "type": "->",
            "function": "handle",
            "file": "/var/www/webservice/vendor/symfony/http-kernel/Kernel.php",
            "line": 188,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpFoundation\\Request"
                ],
                [
                    "integer",
                    1
                ],
                [
                    "boolean",
                    true
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\HttpKernel",
            "short_class": "Kernel",
            "class": "Symfony\\Component\\HttpKernel\\Kernel",
            "type": "->",
            "function": "handle",
            "file": "/var/www/webservice/public/index.php",
            "line": 37,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpFoundation\\Request"
                ]
            ]
        }
    ]
}
</code>```

I did of course do some research on my own and had a look at both:

Unable to generate an IRI for the item of type

api platform - Unable to generate an IRI for the item

Request validator : validate an IRI

https://github.com/api-platform/core/issues/830

So I've added an id (which is not needed since this entity is just used for post's), cleared the cash, checked the getters and setters but all to no avail.

The entity currently looks like this

```<code>/**
 * The register Entity
 *
 * @ApiResource(
 *      collectionOperations={
 *          "post"={"method"="POST", "path"="/register", "controller" = RegisterController::class}
 *      }
 * )
 */

class Register implements \Serializable
{
    /**
     * The unique identifier of this user <br /><b>Schema:</b> <a href="http://schema.org/identifier">https://schema.org/identifier</a>
     *
     * @var integer
     *
     * @ApiProperty(iri="https://schema.org/identifier", identifier=true)
     */
    protected $id;

    /**
     * The unique username of this user, used as a security credential alongside the password
     *
     * @var string
     *
     */
    protected $username;

    /**
     * The non-unique e-mail address, used to contact the user on security issues
     *
     * @var string
     *
     * @ApiProperty(iri="http://schema.org/email")
     */
    protected $email;

    /**
     * The non-unique password of this user, used as a security credential alongside the e-mail. Passwords are hashed in the database and can therefore never be rendered or viewed
     *
     * @var string
     *
     */
    protected $password;

    /**
     * Serializing the user data that is set into the session
     */
    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
                $this->id,
                $this->username,
                $this->password,
                $this->email
        ));
    }

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

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

    /**
     * Get id.
     *
     * @return User
     */
    public function setId($id)
    {
        $this->id= $id;

        return $this;
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * 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;
    }
}
</code>```

The controller (not quite finished but trying to solve this first):

```<code>/**
 * Register controller
 *
 * @category   Controller
 * @package    XXX\UserBundle
 * @subpackage Controller
 *
 */

namespace App\XXX\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\XXX\UserBundle\Service\UserService;
use App\XXX\UserBundle\Entity\User;
use App\XXX\UserBundle\Entity\Register;

class RegisterController extends Controller
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService= $userService;
    }

    public function __invoke(Register $data): Register
    {
        //$this->myService->doSomething($data);

        /*
        $user = $this->userService->register($data);

        if($user){
            //  $token = JWTManager::create($user)

            // voorbeeld

            // return serialized token
            // @var JWTManager $jwtManager
            $jwtManager = $this->get('lexik_jwt_authentication.jwt_manager');
            $jwt = $jwtManager->create($user);
            $response = new JsonResponse();
            $response->setData(array('token' => $jwt));
            return $response;
        }
         */
        return $data;
    }

}
</code>```

and last but not least  config/routes/api_platform.yaml

```<code>api_platform:
    resource: .
    type: api_platform
    prefix: /api

user_register:
    path: '/api/register'
    methods:  ['POST']
    defaults:
        _controller: '\App\XXX\UserBundle\RegisterController::class'
        _api_resource_class: 'App\XXX\UserBundle\Entity\Register'
        _api_item_operation_name: 'register'

user_reminder:
    path: '/api/reset'
    methods:  ['POST']
    defaults:
        _controller: '\App\XXX\UserBundle\ResetController::class'
        _api_resource_class: 'App\XXX\UserBundle\Entity\Reset'
        _api_item_operation_name: 'rest'

user_login:
    path: '/api/login'
    methods:  ['POST']
    defaults:
        _controller: '\App\XXX\UserBundle\LoginController::class'
        _api_resource_class: 'App\XXX\UserBundle\Entity\Login'
        _api_item_operation_name: 'login'
</code>```

I'm probably overlooking something basic here, but I've spent hours on it and just can't seem to get it to work.

--- Update ---
I changed everything back to basic (for testing and error hunting) and it just wont fly. Added get/set and even made ID public, it just wont work. Even this simple class below gets me the IRI error. So basically everything I try that isn't an ORM object fails.

```<code>use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;

/**
 * The user Entity
 *
 * @ApiResource(
 *      itemOperations={
 *          "get"={"method"="GET"},
 *      },
 *      collectionOperations={
 *          "get"={"method"="GET"},
 *          "register"={"route_name"="register_register"},
 *      },
 * )
 */

class Register
{
    /**
     * The unique identifier of this user <br /><b>Schema:</b> <a href="http://schema.org/identifier">https://schema.org/identifier</a>
     *
     * @var integer
     *
     * @ApiProperty(identifier=true)
     */
    public  $id;

    /**
     * Get id.
     *
     * @return int
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}
</code>```

答:
I am new to api platform and had the same issue. The following solution worked for me. Add a normalization_context to the post method in collectionOperations annotation section.

Using your first Register class you would have:

```<code>/**
     * The register Entity
     *
     * @ApiResource(
     *      collectionOperations={
     *          "post"=
     *           {
     *              "method"="POST",
     *              "path"="/register",
     *              "controller" = RegisterController::class,
     *              "normalization_context"={"groups"={"common:read"}}
     *           }
     *      }
     * )
     */

    class Register implements \Serializable
    {
</code>```

Then put the same group above the fields/properties you wish to return. Continuing with the Register class above: the value added above each property is @Groups("common:read") :

```<code>/**
     * The unique identifier of this user <br /><b>Schema:</b> <a href="http://schema.org/identifier">https://schema.org/identifier</a>
     *
     * @var integer
     *
     * @Groups("common:read")
     *
     * @ApiProperty(iri="https://schema.org/identifier", identifier=true)
     */
    protected $id;

    /**
     * The unique username of this user, used as a security credential alongside the password
     *
     * @var string
     *
     * @Groups("common:read")
     *
     */
    protected $username;

    /**
     * The non-unique e-mail address, used to contact the user on security issues
     *
     * @var string
     *
     * @Groups("common:read")
     *
     * @ApiProperty(iri="http://schema.org/email")
     */
    protected $email;
</code>```

Body:
I'm trying to setup my first api-platform instance and have run into some presumably noob questions around IDE. What I'm trying to do is setting up an register and reset entity in order to deal with registrations and password reminders from an app. And then have the entity's passed to a custom controller to do some checks, balances and mails afterwards (haven’t gotten around to that yet). But I keep running into this error when posting to my custom entities:

{
    "@context": "/api/contexts/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "Unable to generate an IRI for the item of type \"App\\XXX\\UserBundle\\Entity\\Register\"",
    "trace": [
        {
            "namespace": "",
            "short_class": "",
            "class": "",
            "type": "",
            "function": "",
            "file": "/var/www/webservice/vendor/api-platform/core/src/Bridge/Symfony/Routing/IriConverter.php",
            "line": 116,
            "args": []
        },
        {
            "namespace": "ApiPlatform\\Core\\Bridge\\Symfony\\Routing",
            "short_class": "IriConverter",
            "class": "ApiPlatform\\Core\\Bridge\\Symfony\\Routing\\IriConverter",
            "type": "->",
            "function": "getIriFromItem",
            "file": "/var/www/webservice/vendor/api-platform/core/src/JsonLd/Serializer/ItemNormalizer.php",
            "line": 71,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ]
            ]
        },
        {
            "namespace": "ApiPlatform\\Core\\JsonLd\\Serializer",
            "short_class": "ItemNormalizer",
            "class": "ApiPlatform\\Core\\JsonLd\\Serializer\\ItemNormalizer",
            "type": "->",
            "function": "normalize",
            "file": "/var/www/webservice/vendor/symfony/serializer/Serializer.php",
            "line": 138,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ],
                [
                    "string",
                    "jsonld"
                ],
                [
                    "array",
                    {
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "resource_class": [
                            "string",
                            "App\\XXX\\UserBundle\\Entity\\Register"
                        ],
                        "request_uri": [
                            "string",
                            "/api/register"
                        ],
                        "uri": [
                            "string",
                            "http://webservice.local/api/register"
                        ],
                        "resources": [
                            "object",
                            "ApiPlatform\\Core\\Serializer\\ResourceList"
                        ],
                        "jsonld_has_context": [
                            "boolean",
                            true
                        ]
                    }
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\Serializer",
            "short_class": "Serializer",
            "class": "Symfony\\Component\\Serializer\\Serializer",
            "type": "->",
            "function": "normalize",
            "file": "/var/www/webservice/vendor/symfony/serializer/Serializer.php",
            "line": 111,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ],
                [
                    "string",
                    "jsonld"
                ],
                [
                    "array",
                    {
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "resource_class": [
                            "string",
                            "App\\XXX\\UserBundle\\Entity\\Register"
                        ],
                        "request_uri": [
                            "string",
                            "/api/register"
                        ],
                        "uri": [
                            "string",
                            "http://webservice.local/api/register"
                        ],
                        "resources": [
                            "object",
                            "ApiPlatform\\Core\\Serializer\\ResourceList"
                        ]
                    }
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\Serializer",
            "short_class": "Serializer",
            "class": "Symfony\\Component\\Serializer\\Serializer",
            "type": "->",
            "function": "serialize",
            "file": "/var/www/webservice/vendor/api-platform/core/src/EventListener/SerializeListener.php",
            "line": 67,
            "args": [
                [
                    "object",
                    "App\\XXX\\UserBundle\\Entity\\Register"
                ],
                [
                    "string",
                    "jsonld"
                ],
                [
                    "array",
                    {
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "resource_class": [
                            "string",
                            "App\\XXX\\UserBundle\\Entity\\Register"
                        ],
                        "request_uri": [
                            "string",
                            "/api/register"
                        ],
                        "uri": [
                            "string",
                            "http://webservice.local/api/register"
                        ],
                        "resources": [
                            "object",
                            "ApiPlatform\\Core\\Serializer\\ResourceList"
                        ]
                    }
                ]
            ]
        },
        {
            "namespace": "ApiPlatform\\Core\\EventListener",
            "short_class": "SerializeListener",
            "class": "ApiPlatform\\Core\\EventListener\\SerializeListener",
            "type": "->",
            "function": "onKernelView",
            "file": "/var/www/webservice/vendor/symfony/event-dispatcher/EventDispatcher.php",
            "line": 212,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent"
                ],
                [
                    "string",
                    "kernel.view"
                ],
                [
                    "object",
                    "Symfony\\Component\\EventDispatcher\\EventDispatcher"
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\EventDispatcher",
            "short_class": "EventDispatcher",
            "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
            "type": "->",
            "function": "doDispatch",
            "file": "/var/www/webservice/vendor/symfony/event-dispatcher/EventDispatcher.php",
            "line": 44,
            "args": [
                [
                    "array",
                    [
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\Validator\\EventListener\\ValidateListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ],
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\EventListener\\WriteListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ],
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\EventListener\\SerializeListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ],
                        [
                            "array",
                            [
                                [
                                    "object",
                                    "ApiPlatform\\Core\\EventListener\\RespondListener"
                                ],
                                [
                                    "string",
                                    "onKernelView"
                                ]
                            ]
                        ]
                    ]
                ],
                [
                    "string",
                    "kernel.view"
                ],
                [
                    "object",
                    "Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent"
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\EventDispatcher",
            "short_class": "EventDispatcher",
            "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
            "type": "->",
            "function": "dispatch",
            "file": "/var/www/webservice/vendor/symfony/http-kernel/HttpKernel.php",
            "line": 154,
            "args": [
                [
                    "string",
                    "kernel.view"
                ],
                [
                    "object",
                    "Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent"
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\HttpKernel",
            "short_class": "HttpKernel",
            "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
            "type": "->",
            "function": "handleRaw",
            "file": "/var/www/webservice/vendor/symfony/http-kernel/HttpKernel.php",
            "line": 66,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpFoundation\\Request"
                ],
                [
                    "integer",
                    1
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\HttpKernel",
            "short_class": "HttpKernel",
            "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
            "type": "->",
            "function": "handle",
            "file": "/var/www/webservice/vendor/symfony/http-kernel/Kernel.php",
            "line": 188,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpFoundation\\Request"
                ],
                [
                    "integer",
                    1
                ],
                [
                    "boolean",
                    true
                ]
            ]
        },
        {
            "namespace": "Symfony\\Component\\HttpKernel",
            "short_class": "Kernel",
            "class": "Symfony\\Component\\HttpKernel\\Kernel",
            "type": "->",
            "function": "handle",
            "file": "/var/www/webservice/public/index.php",
            "line": 37,
            "args": [
                [
                    "object",
                    "Symfony\\Component\\HttpFoundation\\Request"
                ]
            ]
        }
    ]
}

I did of course do some research on my own and had a look at both:

Unable to generate an IRI for the item of type

api platform - Unable to generate an IRI for the item

Request validator : validate an IRI

https://github.com/api-platform/core/issues/830

So I've added an id (which is not needed since this entity is just used for post's), cleared the cash, checked the getters and setters but all to no avail.

The entity currently looks like this

/**
 * The register Entity
 *
 * @ApiResource(
 *      collectionOperations={
 *          "post"={"method"="POST", "path"="/register", "controller" = RegisterController::class}
 *      }
 * )
 */

class Register implements \Serializable
{
    /**
     * The unique identifier of this user
Schema: https://schema.org/identifier
     *
     * @var integer
     *
     * @ApiProperty(iri="https://schema.org/identifier", identifier=true)
     */
    protected $id;

    /**
     * The unique username of this user, used as a security credential alongside the password
     *
     * @var string
     *
     */
    protected $username;

    /**
     * The non-unique e-mail address, used to contact the user on security issues
     *
     * @var string
     *
     * @ApiProperty(iri="http://schema.org/email")
     */
    protected $email;

    /**
     * The non-unique password of this user, used as a security credential alongside the e-mail. Passwords are hashed in the database and can therefore never be rendered or viewed
     *
     * @var string
     *
     */
    protected $password;

    /**
     * Serializing the user data that is set into the session
     */
    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
                $this->id,
                $this->username,
                $this->password,
                $this->email
        ));
    }

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

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

    /**
     * Get id.
     *
     * @return User
     */
    public function setId($id)
    {
        $this->id= $id;

        return $this;
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * 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;
    }
}

The controller (not quite finished but trying to solve this first):

/**
 * Register controller
 *
 * @category   Controller
 * @package    XXX\UserBundle
 * @subpackage Controller
 *
 */

namespace App\XXX\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\XXX\UserBundle\Service\UserService;
use App\XXX\UserBundle\Entity\User;
use App\XXX\UserBundle\Entity\Register;

class RegisterController extends Controller
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService= $userService;
    }

    public function __invoke(Register $data): Register
    {
        //$this->myService->doSomething($data);

        /*
        $user = $this->userService->register($data);

        if($user){
            //  $token = JWTManager::create($user)

            // voorbeeld

            // return serialized token
            // @var JWTManager $jwtManager
            $jwtManager = $this->get('lexik_jwt_authentication.jwt_manager');
            $jwt = $jwtManager->create($user);
            $response = new JsonResponse();
            $response->setData(array('token' => $jwt));
            return $response;
        }
         */
        return $data;
    }

}

and last but not least  config/routes/api_platform.yaml

api_platform:
    resource: .
    type: api_platform
    prefix: /api

user_register:
    path: '/api/register'
    methods:  ['POST']
    defaults:
        _controller: '\App\XXX\UserBundle\RegisterController::class'
        _api_resource_class: 'App\XXX\UserBundle\Entity\Register'
        _api_item_operation_name: 'register'

user_reminder:
    path: '/api/reset'
    methods:  ['POST']
    defaults:
        _controller: '\App\XXX\UserBundle\ResetController::class'
        _api_resource_class: 'App\XXX\UserBundle\Entity\Reset'
        _api_item_operation_name: 'rest'

user_login:
    path: '/api/login'
    methods:  ['POST']
    defaults:
        _controller: '\App\XXX\UserBundle\LoginController::class'
        _api_resource_class: 'App\XXX\UserBundle\Entity\Login'
        _api_item_operation_name: 'login'

I'm probably overlooking something basic here, but I've spent hours on it and just can't seem to get it to work.

--- Update ---
I changed everything back to basic (for testing and error hunting) and it just wont fly. Added get/set and even made ID public, it just wont work. Even this simple class below gets me the IRI error. So basically everything I try that isn't an ORM object fails.

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;

/**
 * The user Entity
 *
 * @ApiResource(
 *      itemOperations={
 *          "get"={"method"="GET"},
 *      },
 *      collectionOperations={
 *          "get"={"method"="GET"},
 *          "register"={"route_name"="register_register"},
 *      },
 * )
 */

class Register
{
    /**
     * The unique identifier of this user
Schema: https://schema.org/identifier
     *
     * @var integer
     *
     * @ApiProperty(identifier=true)
     */
    public  $id;

    /**
     * Get id.
     *
     * @return int
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

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

Body:
I am new to api platform and had the same issue. The following solution worked for me. Add a normalization_context to the post method in collectionOperations annotation section.

Using your first Register class you would have:

/**
     * The register Entity
     *
     * @ApiResource(
     *      collectionOperations={
     *          "post"=
     *           {
     *              "method"="POST",
     *              "path"="/register",
     *              "controller" = RegisterController::class,
     *              "normalization_context"={"groups"={"common:read"}}
     *           }
     *      }
     * )
     */

    class Register implements \Serializable
    {

Then put the same group above the fields/properties you wish to return. Continuing with the Register class above: the value added above each property is @Groups("common:read") :

/**
     * The unique identifier of this user <br /><b>Schema:</b> <a href="http://schema.org/identifier">https://schema.org/identifier</a>
     *
     * @var integer
     *
     * @Groups("common:read")
     *
     * @ApiProperty(iri="https://schema.org/identifier", identifier=true)
     */
    protected $id;

    /**
     * The unique username of this user, used as a security credential alongside the password
     *
     * @var string
     *
     * @Groups("common:read")
     *
     */
    protected $username;

    /**
     * The non-unique e-mail address, used to contact the user on security issues
     *
     * @var string
     *
     * @Groups("common:read")
     *
     * @ApiProperty(iri="http://schema.org/email")
     */
    protected $email;


来源: stackexchange

问:
How to reset intellisense in VS Code?
If you make a code change while VsCode is debugging, the intellisense sometimes appears to malfunction with false compile errors.  Fastest way to reset or correct it?</p>

答: You may Ctrl+Shift+P or F1, then write "reset.." in command pallete, and choose in popup list "C/C++ Reset IntelliSense database".

ContentLicense: CC BY-SA 3.0

Title: How to reset intellisense in VS Code?

ContentLicense: CC BY-SA 4.0


问:
How to create a scatter plot in pandas grouped by time of day
I would like to create a scatter plot using Pandas where the values are grouped by time of day and coloured/styled differently based on the day. The code snippet below will create a scatter plot of two time-series.

```<code>import pandas as pd
idx = pd.date_range('2019-01-01', periods=48, freq='H')
x = pd.Series(range(len(idx)), index=idx)
y = x
d = {'x': x, 'y': y}
df = pd.DataFrame(data=d)
df.plot.scatter(x='x', y='y')
</code>```

However, when I tried to aggregate the data in a list by time of day, I was unable to plot them as scatter:

```<code>df['time'] = df.index.time
df_agg= df.groupby('time').agg(list)
</code>```

答:
Since you want to perform a scatter plot and keep all the data, I suggest not using groupby. Instead, the hour and day methods of DatetimeIndex objects provide a simple way to color by day and plot by daytime hour.

import pandas as pd
import matplotlib.pyplot as plt

idx = pd.date_range('2019-01-01', periods=48, freq='H')
x = pd.Series(range(len(idx)), index=idx)
y = x
# add 'hour' and 'day' columns in the dataframe
d = {'x': x, 'y': y, 'hour': idx.hour, 'day': idx.day}
df = pd.DataFrame(data=d)
# use 'hour' as x axis to plot, and 'day' as marker color
df.plot.scatter(x='hour', y='y', c='day', colormap='rainbow')
plt.show()
```

Body:
I would like to create a scatter plot using Pandas where the values are grouped by time of day and coloured/styled differently based on the day. The code snippet below will create a scatter plot of two time-series.

import pandas as pd
idx = pd.date_range('2019-01-01', periods=48, freq='H')
x = pd.Series(range(len(idx)), index=idx)
y = x
d = {'x': x, 'y': y}
df = pd.DataFrame(data=d)
df.plot.scatter(x='x', y='y')

However, when I tried to aggregate the data in a list by time of day, I was unable to plot them as scatter:

df['time'] = df.index.time
df_agg= df.groupby('time').agg(list)


问:
How can I remove @link tag and its contents between { and } from a javadoc comment?
I am trying to analyse Javadoc comments. I do not need the contents of @link tag. How can I remove this?
The general format is {@link.........}

With this code below, I get an error: ValueError: unexpected '{' in field name

```<code>with open("comments.txt", 'r') as f:
        for line in f:
           remove_link_tag = re.sub('{@link(.*?)}', lambda m: "
              {@link{}}>".format(
                m.group(1).replace(".", "").replace(",",
                  "").replace(";",                                                                                "")), line, flags=re.DOTALL)
</code>```

INPUT:

```<code>/**
    * Adds the specified source and target vertices to the graph, if not already included, and
    * creates a new edge and adds it to the specified graph similarly to the
    * {@link Graph#addEdge(Object, Object)} method.
    * {@code sourceVertex}
    * @param graph the graph for which the specified edge to be added
    * @param sourceVertex source vertex of the edge
    * @param targetVertex target vertex of the edge
    * @param <V> the graph vertex type
    * @param <E> the graph edge type
    *
    * @return The newly created edge if added to the graph, otherwise <code>
    * null</code>.
    */
</code>```

OUTPUT

```<code>/**
    * Adds the specified source and target vertices to the graph, if not already included, and
    * creates a new edge and adds it to the specified graph similarly to the
    * method.
    *
    * {@code sourceVertex}
    * @param graph the graph for which the specified edge to be added
    * @param sourceVertex source vertex of the edge
    * @param targetVertex target vertex of the edge
    * @param <V> the graph vertex type
    * @param <E> the graph edge type
    *
    * @return The newly created edge if added to the graph, otherwise <code>
    * null</code>.
    */
</code>```

答:
Sipmly as:

```<code>import re

input = """/**
    * Adds the specified source and target vertices to the graph, if not already included, and
    * creates a new edge and adds it to the specified graph similarly to the
    * {@link Graph#addEdge(Object, Object)} method.
    *
    * @param graph the graph for which the specified edge to be added
    * @param sourceVertex source vertex of the edge
    * @param targetVertex target vertex of the edge
    * @param <V> the graph vertex type
    * @param <E> the graph edge type
    *
    * @return The newly created edge if added to the graph, otherwise <code>
    * null</code>.
    */"""

out = re.sub('{@link.*?}', '', input)
</code>```

Output:

```<code>/**
     * Adds the specified source and target vertices to the graph, if not already included, and
     * creates a new edge and adds it to the specified graph similarly to the
     *  method.
     *
     * @param graph the graph for which the specified edge to be added
     * @param sourceVertex source vertex of the edge
     * @param targetVertex target vertex of the edge
     * @param <V> the graph vertex type
     * @param <E> the graph edge type
     *
     * @return The newly created edge if added to the graph, otherwise <code>
     * null</code>.
     */
</code>```

Body:
I am trying to analyse Javadoc comments. I do not need the contents of @link tag. How can I remove this?
The general format is {@link.........}

With this code below, I get an error: ValueError: unexpected '{' in field name

with open("comments.txt", 'r') as f:
        for line in f:
           remove_link_tag = re.sub('{@link(.*?)}', lambda m: "
              {@link{}}>".format(
                m.group(1).replace(".", "").replace(",",
                  "").replace(";",                                                                                "")), line, flags=re.DOTALL)

INPUT:

/**
    * Adds the specified source and target vertices to the graph, if not already included, and
    * creates a new edge and adds it to the specified graph similarly to the
    * {@link Graph#addEdge(Object, Object)} method.
    * {@code sourceVertex}
    * @param graph the graph for which the specified edge to be added
    * @param sourceVertex source vertex of the edge
    * @param targetVertex target vertex of the edge
    * @param <V> the graph vertex type
    * @param <E> the graph edge type
    *
    * @return The newly created edge if added to the graph, otherwise
    * null.
    */

OUTPUT

/**
    * Adds the specified source and target vertices to the graph, if not already included, and
    * creates a new edge and adds it to the specified graph similarly to the
    * method.
    *
    * {@code sourceVertex}
    * @param graph the graph for which the specified edge to be added
    * @param sourceVertex source vertex of the edge
    * @param targetVertex target vertex of the edge
    * @param <V> the graph vertex type
    * @param <E> the graph edge type
    *
    * @return The newly created edge if added to the graph, otherwise
    * null.
    */

Body:
Sipmly as:

import re

input = """/**
    * Adds the specified source and target vertices to the graph, if not already included, and
    * creates a new edge and adds it to the specified graph similarly to the
    * {@link Graph#addEdge(Object, Object)} method.
    *
    * @param graph the graph for which the specified edge to be added
    * @param sourceVertex source vertex of the edge
    * @param targetVertex target vertex of the edge
    * @param <V> the graph vertex type
    * @param <E> the graph edge type
    *
    * @return The newly created edge if added to the graph, otherwise <code>
    * null</code>.
    */"""

out = re.sub('{@link.*?}', '', input)

Output:

/**
     * Adds the specified source and target vertices to the graph, if not already included, and
     * creates a new edge and adds it to the specified graph similarly to the
     *  method.
     *
     * @param graph the graph for which the specified edge to be added
     * @param sourceVertex source vertex of the edge
     * @param targetVertex target vertex of the edge
     * @param <V> the graph vertex type
     * @param <E> the graph edge type
     *
     * @return The newly created edge if added to the graph, otherwise <code>
     * null</code>.
     */


问:
Angular Universal forward IP from client for all SSR API calls
I determine the user's city by IP and want the assembled page to refer to a specific city. How can I forward IP to all api requests that SSR makes from the backend? Now there is always 127.0.0.1

```<code>// All regular routes use the Universal engine
app.get('*', (req, res) => {
    res.render('index', { req });
});
</code>```

what should I change in this code, to have x-ip header on PHP backend then API called from SSR

答:
You could try something like this

You need to provide angular with the client IP

server.ts

```<code>import { REQUEST } from '@nguniversal/express-engine/tokens';

//..
app.engine('html', (_, options, callback) =>
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: REQUEST,
        useValue: options.req, //Provides the request to angular
      },
    ],
  })(_, options, callback)
)
</code>```

Then, use a HTTP Interceptor to get the IP adress from the http request and add it to the request sent to the API, e.g. using a custom header like below (or add it a

injector.ts

```<code>import { Injectable, Inject, Optional } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';

@Injectable()
export class IPHttpInterceptor implements HttpInterceptor {
  constructor(@Optional() @Inject(REQUEST) httpRequest: any) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const ip = httpRequest.connection.remoteAddress;

    if(ip) //ip wil be undefined client side
    {
        request = request.clone({
          setHeaders: {
            Client-IP: ip
          }
        });
    }
    return next.handle(request);
  }
}
</code>```

Provide your http interceptor in your app module

app.module.ts

```<code>import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
//...
 providers: [
 { provide: HTTP_INTERCEPTORS, useClass: IPHttpInterceptor, multi: true }
</code>```

Modify your API to parse to get the IP from the custom header above

Body:
I determine the user's city by IP and want the assembled page to refer to a specific city. How can I forward IP to all api requests that SSR makes from the backend? Now there is always 127.0.0.1

// All regular routes use the Universal engine
app.get('*', (req, res) => {
    res.render('index', { req });
});

what should I change in this code, to have x-ip header on PHP backend then API called from SSR

Body:
You could try something like this

You need to provide angular with the client IP

server.ts

import { REQUEST } from '@nguniversal/express-engine/tokens';

//..
app.engine('html', (_, options, callback) =>
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: REQUEST,
        useValue: options.req, //Provides the request to angular
      },
    ],
  })(_, options, callback)
)

Then, use a HTTP Interceptor to get the IP adress from the http request and add it to the request sent to the API, e.g. using a custom header like below (or add it a

injector.ts

import { Injectable, Inject, Optional } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { REQUEST } from '@nguniversal/express-engine/tokens';

@Injectable()
export class IPHttpInterceptor implements HttpInterceptor {
  constructor(@Optional() @Inject(REQUEST) httpRequest: any) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const ip = httpRequest.connection.remoteAddress;

    if(ip) //ip wil be undefined client side
    {
        request = request.clone({
          setHeaders: {
            Client-IP: ip
          }
        });
    }
    return next.handle(request);
  }
}

Provide your http interceptor in your app module

app.module.ts

import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
//...
 providers: [
 { provide: HTTP_INTERCEPTORS, useClass: IPHttpInterceptor, multi: true }

Modify your API to parse to get the IP from the custom header above


问:
How do I send an array with fetch? (Javascript)
I'm trying to send an array using fetch that looks like this:

```<code>{"cards":[[189,2],[211,2],[238,2],[778,2],[985,2],[1008,2],[1073,2],[1171,2],[48886,2],[49161,2],[49164,2],[49184,1],[49356,2],[50372,2],[51722,1],[52422,2]],"heroes":[1066],"format":2}
</code>```

Here is what I am trying:

```<code> getCardsForDeck = deck => {
    var stringifiedDeck = JSON.stringify(deck);
    console.log("stringifiedDeck:" + stringifiedDeck);
    fetch(`http://localhost:3001/api/getCardsForDeck`, {
      method: "PUT",
      body: stringifiedDeck
    })
      .then(cards => cards.json())
      .then(res => this.setState({ cards: res.cards }));
  };
</code>```

I am getting an error though:

```<code>Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
</code>```

How do I send this data if not with JSON.stringify() or do I have to edit the data to remove the brackets?

Upon checking the api in the network tab it gives me this:

```<code>     SyntaxError: Unexpected token o in JSON at position 1
[0]     at JSON.parse (<anonymous>)
[0]     at parse (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\types\json.js:89:19)
[0]     at C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\read.js:121:18
[0]     at invokeCallback (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:224:16)
[0]     at done (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:213:7)
[0]     at IncomingMessage.onEnd (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:273:7)
[0]     at IncomingMessage.emit (events.js:194:15)
[0]     at endReadableNT (_stream_readable.js:1125:12)
[0]     at process._tickCallback (internal/process/next_tick.js:63:19)
[0] SyntaxError: Unexpected token o in JSON at position 1
[0]     at JSON.parse (<anonymous>)
[0]     at parse (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\types\json.js:89:19)
[0]     at C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\read.js:121:18
[0]     at invokeCallback (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:224:16)
[0]     at done (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:213:7)
[0]     at IncomingMessage.onEnd (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:273:7)
[0]     at IncomingMessage.emit (events.js:194:15)
[0]     at endReadableNT (_stream_readable.js:1125:12)
[0]     at process._tickCallback (internal/process/next_tick.js:63:19)
</code>```

答:
You seem to be expecting http://localhost:3001/api/getCardsForDeck to send JSON back after you send JSON to it. Most likely it's responding with HTML, not JSON.

There are two other errors in that code:

You need to say what you're sending, since it's not the default URI-encoded data:

```<code>fetch(`http://localhost:3001/api/getCardsForDeck`, {
  method: "PUT",
  body: stringifiedDeck,
  headers: {                              // ***
    "Content-Type": "application/json"    // ***
  }                                       // ***
})
</code>```

You need to check the status of the response. (Everyone misses this out.) The simplest way is to check the ok flag on the response:

```<code>fetch(`http://localhost:3001/api/getCardsForDeck`, {
  method: "PUT",
  body: stringifiedDeck,
  headers: {
    "Content-Type": "application/json"
  }
})
.then(response => {
  if (!response.ok) {                                  // ***
    throw new Error("HTTP error " + response.status);  // ***
  }                                                    // ***
  // ...use `response.json`, `response.text`, etc. here
})
.catch(error => {
  // ...handle/report error
});
</code>```

Body:
I'm trying to send an array using fetch that looks like this:

{"cards":[[189,2],[211,2],[238,2],[778,2],[985,2],[1008,2],[1073,2],[1171,2],[48886,2],[49161,2],[49164,2],[49184,1],[49356,2],[50372,2],[51722,1],[52422,2]],"heroes":[1066],"format":2}

Here is what I am trying:

 getCardsForDeck = deck => {
    var stringifiedDeck = JSON.stringify(deck);
    console.log("stringifiedDeck:" + stringifiedDeck);
    fetch(`http://localhost:3001/api/getCardsForDeck`, {
      method: "PUT",
      body: stringifiedDeck
    })
      .then(cards => cards.json())
      .then(res => this.setState({ cards: res.cards }));
  };

I am getting an error though:

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

How do I send this data if not with JSON.stringify() or do I have to edit the data to remove the brackets?

Upon checking the api in the network tab it gives me this:

     SyntaxError: Unexpected token o in JSON at position 1
[0]     at JSON.parse (<anonymous>)
[0]     at parse (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\types\json.js:89:19)
[0]     at C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\read.js:121:18
[0]     at invokeCallback (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:224:16)
[0]     at done (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:213:7)
[0]     at IncomingMessage.onEnd (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:273:7)
[0]     at IncomingMessage.emit (events.js:194:15)
[0]     at endReadableNT (_stream_readable.js:1125:12)
[0]     at process._tickCallback (internal/process/next_tick.js:63:19)
[0] SyntaxError: Unexpected token o in JSON at position 1
[0]     at JSON.parse (<anonymous>)
[0]     at parse (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\types\json.js:89:19)
[0]     at C:\Users\User\projects\webapp\deck-editor\backend\node_modules\body-parser\lib\read.js:121:18
[0]     at invokeCallback (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:224:16)
[0]     at done (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:213:7)
[0]     at IncomingMessage.onEnd (C:\Users\User\projects\webapp\deck-editor\backend\node_modules\raw-body\index.js:273:7)
[0]     at IncomingMessage.emit (events.js:194:15)
[0]     at endReadableNT (_stream_readable.js:1125:12)
[0]     at process._tickCallback (internal/process/next_tick.js:63:19)

Body:
You seem to be expecting http://localhost:3001/api/getCardsForDeck to send JSON back after you send JSON to it. Most likely it's responding with HTML, not JSON.

There are two other errors in that code:

You need to say what you're sending, since it's not the default URI-encoded data:

fetch(`http://localhost:3001/api/getCardsForDeck`, {
  method: "PUT",
  body: stringifiedDeck,
  headers: {                              // ***
    "Content-Type": "application/json"    // ***
  }                                       // ***
})

You need to check the status of the response. (Everyone misses this out.) The simplest way is to check the ok flag on the response:

fetch(`http://localhost:3001/api/getCardsForDeck`, {
  method: "PUT",
  body: stringifiedDeck,
  headers: {
    "Content-Type": "application/json"
  }
})
.then(response => {
  if (!response.ok) {                                  // ***
    throw new Error("HTTP error " + response.status);  // ***
  }                                                    // ***
  // ...use `response.json`, `response.text`, etc. here
})
.catch(error => {
  // ...handle/report error
});


问:
Not in search string - It works when it is
Hope you can help.
I have column A and B
In A, I need to replace all text containing "Forsikringspræmie" with "" (Blank)

This code works. Sub KSV_Remove_Forsikringspræmie()

But in Column B, I need the Opposit, to happen.
And the code Sub KSV_Remove_Not_Forsikringspræmie() dosent work.

```<code>Sub KSV_Remove_Forsikringspræmie()
    Dim KSV_SrchRng As Range, cel As Range
    Set KSV_SrchRng = Range("A1:A99")
    For Each cel In KSV_SrchRng
      If InStr(1, cel.Value, "Forsikringspræmie") > 0 Then
         cel.Value = ""
      End If
    Next cel
End Sub

Sub KSV_Remove_Not_Forsikringspræmie()
    Dim KSV_SrchRng As Range, cel As Range
    Set KSV_SrchRng = Range("B1:B99")
    For Each cel In KSV_SrchRng
      If InStr(1, cel.Value, Not "Forsikringspræmie") Then
         cel.Value = ""
      End If
    Next cel
End Sub
</code>```

答:
I think you may just be placing the Not in the wrong place. Try this:

```<code>Sub KSV_Remove_Not_Forsikringspræmie()
    Dim KSV_SrchRng As Range, cel As Range
    Set KSV_SrchRng = Range("B1:B99")
    For Each cel In KSV_SrchRng
      If Not (InStr(1, cel.Value, "Forsikringspræmie")) Then
         cel.Value = ""
      End If
    Next cel
End Sub
</code>```

Body:
Hope you can help.
I have column A and B
In A, I need to replace all text containing "Forsikringspræmie" with "" (Blank)

This code works. Sub KSV_Remove_Forsikringspræmie()

But in Column B, I need the Opposit, to happen.
And the code Sub KSV_Remove_Not_Forsikringspræmie() dosent work.

Sub KSV_Remove_Forsikringspræmie()
    Dim KSV_SrchRng As Range, cel As Range
    Set KSV_SrchRng = Range("A1:A99")
    For Each cel In KSV_SrchRng
      If InStr(1, cel.Value, "Forsikringspræmie") > 0 Then
         cel.Value = ""
      End If
    Next cel
End Sub

Sub KSV_Remove_Not_Forsikringspræmie()
    Dim KSV_SrchRng As Range, cel As Range
    Set KSV_SrchRng = Range("B1:B99")
    For Each cel In KSV_SrchRng
      If InStr(1, cel.Value, Not "Forsikringspræmie") Then
         cel.Value = ""
      End If
    Next cel
End Sub

Body:
I think you may just be placing the Not in the wrong place. Try this:

Sub KSV_Remove_Not_Forsikringspræmie()
    Dim KSV_SrchRng As Range, cel As Range
    Set KSV_SrchRng = Range("B1:B99")
    For Each cel In KSV_SrchRng
      If Not (InStr(1, cel.Value, "Forsikringspræmie")) Then
         cel.Value = ""
      End If
    Next cel
End Sub


问:
How to explode a Datastream with a json array into DataStream of individual array elements
I have a Datastream[ObjectNode] which I read as deserialized json from a kafka topic. One of the element of this ObjectNode is actually an array of events. This array has varying length. The incoming json stream looks like this :

```<code>{
    "eventType": "Impression",
    "deviceId": "359849094258487",
    "payload": {
        "vertical_name": "",
        "promo_layout_type": "aa",
        "Customer_Id": "1011851",
        "ecommerce": {
            "promoView": {
                "promotions": [{
                    "name": "/-category_icons_all",
                    "id": "300275",
                    "position": "slot_5_1",
                    "creative": "Central/Gift Card/00000001B890D1739913DDA956AB5C79775991EC"
                }, {
                    "name": "/-category_icons_all",
                    "id": "300276",
                    "position": "slot_6_1",
                    "creative": "Lifestyle/Gift Card/00000001B890D1739913DDA956AB5C79775991EC"
                }, {
                    "name": "/-category_icons_all",
                    "id": "413002",
                    "position": "slot_7_1",
                    "creative": "Uber/Deals/00000001B890D1739913DDA956AB5C79775991EC"
                }]
            }
        }
    }
}
</code>```

I want to be able to explode the promotions array so that each element inside becomes an individual message which can be written to a sink kafka topic. Does Flink provide the explode feature in DataStream and/or Table API?

I have tried to do a RichFlatMap on this stream to be able to collect individual rows but this also just returns me a DataStream[Seq[GenericRecord]] as below:

```<code>class PromoMapper(schema: Schema) extends RichFlatMapFunction[node.ObjectNode,Seq[GenericRecord]] {

  override def flatMap(value: ObjectNode, out: Collector[Seq[GenericRecord]]): Unit = {
    val promos = value.get("payload").get("ecommerce").get("promoView").get("promotions").asInstanceOf[Seq[node.ObjectNode]]

    val record = for{promo <- promos} yield {
      val processedRecord: GenericData.Record = new GenericData.Record(schema)
      promo.fieldNames().asScala.foreach(f => processedRecord.put(f,promo.get(f)))
      processedRecord
    }

    out.collect(record)
  }
}
</code>```

Please help.

答:
Using a flatmap is the right idea (not sure why you bothered with a RichFlatMap, but that's a detail).

Seems like you should be calling out.collect(processedRecord) for each element inside the for loop, rather than once on the Seq produced by that loop.

Body:
I have a Datastream[ObjectNode] which I read as deserialized json from a kafka topic. One of the element of this ObjectNode is actually an array of events. This array has varying length. The incoming json stream looks like this :

{
    "eventType": "Impression",
    "deviceId": "359849094258487",
    "payload": {
        "vertical_name": "",
        "promo_layout_type": "aa",
        "Customer_Id": "1011851",
        "ecommerce": {
            "promoView": {
                "promotions": [{
                    "name": "/-category_icons_all",
                    "id": "300275",
                    "position": "slot_5_1",
                    "creative": "Central/Gift Card/00000001B890D1739913DDA956AB5C79775991EC"
                }, {
                    "name": "/-category_icons_all",
                    "id": "300276",
                    "position": "slot_6_1",
                    "creative": "Lifestyle/Gift Card/00000001B890D1739913DDA956AB5C79775991EC"
                }, {
                    "name": "/-category_icons_all",
                    "id": "413002",
                    "position": "slot_7_1",
                    "creative": "Uber/Deals/00000001B890D1739913DDA956AB5C79775991EC"
                }]
            }
        }
    }
}

I want to be able to explode the promotions array so that each element inside becomes an individual message which can be written to a sink kafka topic. Does Flink provide the explode feature in DataStream and/or Table API?

I have tried to do a RichFlatMap on this stream to be able to collect individual rows but this also just returns me a DataStream[Seq[GenericRecord]] as below:

class PromoMapper(schema: Schema) extends RichFlatMapFunction[node.ObjectNode,Seq[GenericRecord]] {

  override def flatMap(value: ObjectNode, out: Collector[Seq[GenericRecord]]): Unit = {
    val promos = value.get("payload").get("ecommerce").get("promoView").get("promotions").asInstanceOf[Seq[node.ObjectNode]]

    val record = for{promo <- promos} yield {
      val processedRecord: GenericData.Record = new GenericData.Record(schema)
      promo.fieldNames().asScala.foreach(f => processedRecord.put(f,promo.get(f)))
      processedRecord
    }

    out.collect(record)
  }
}

Please help.