问:
How to persist self referencing Doctrine entities?
I have two entities that reference each other and have not null constraints, and am trying to persist them with the following script:

$parentEntity = new \App\Entity\ParentEntity();
$childEntity = new \App\Entity\ChildEntity();
$childEntity->setParentEntity($parentEntity);
$parentEntity->setRootChildEntity($childEntity);

$this->entityManager->persist($parentEntity);
$this->entityManager->persist($childEntity);

printf('$parentEntity->getId(): %s'.PHP_EOL, $parentEntity->getId());
printf('$childEntity->getId(): %s'.PHP_EOL, $childEntity->getId());
printf('$parentEntity->getRootChildEntity()->getId(): %s'.PHP_EOL, $parentEntity->getRootChildEntity()->getId());
printf('$childEntity->getParentEntity()->getId(): %s'.PHP_EOL, $childEntity->getParentEntity()->getId());

$this->entityManager->flush();
```
<p>When executing the script, both entities are populated with integer IDs after being persisted (obtained by the <code>SELECT NEXTVAL</code> queries), but when flushed, instead <code>NULL</code> is used and I get a not null violation.</p>
<p>If I was just getting a foreign key constraint, I would understand why and I could get around it by making the constraints deferrable or bypassing them by temporarily disabling triggers.</p>
<p>But not so with a null violation.  Why is this happening? Without removing the not null constraint which I wish to keep, is there a way around it?</p>
```doctrine.DEBUG: SELECT NEXTVAL('parent_entity_id_seq') [] []
doctrine.DEBUG: SELECT NEXTVAL('child_entity_id_seq') [] []

$parentEntity->getId(): 1
$childEntity->getId(): 1
$parentEntity->getRootChildEntity()->getId(): 1
$childEntity->getParentEntity()->getId(): 1

doctrine.DEBUG: "START TRANSACTION" [] []
doctrine.DEBUG: INSERT INTO parent_entity (id, root_child_entity_id) VALUES (?, ?) {"1":1,"2":null} []
doctrine.DEBUG: "ROLLBACK" [] []
console.CRITICAL: Error thrown while running command "app:add-tenant". Message: "An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "root_child_entity_id" of relation "parent_entity" violates not-null constraint DETAIL:  Failing row contains (1, null)." {"exception":"[object] (Doctrine\\DBAL\\Exception\\NotNullConstraintViolationException(code: 7): An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null). at /srv/api/vendor/doctrine/dbal/src/Driver/API/PostgreSQL/ExceptionConverter.php:51)\n[previous exception] [object] (Doctrine\\DBAL\\Driver\\PDO\\Exception(code: 7): SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null). at /srv/api/vendor/doctrine/dbal/src/Driver/PDO/Exception.php:26)\n[previous exception] [object] (PDOException(code: 23502): SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null). at /srv/api/vendor/doctrine/dbal/src/Driver/PDO/Statement.php:101)","command":"app:add-tenant","message":"An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null)."} []
```
<p>My entities:</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace App\Entity;

use App\Repository\ParentEntityRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class ParentEntity
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\ManyToOne(targetEntity: ChildEntity::class)]
    #[ORM\JoinColumn(nullable: false)]
    private $rootChildEntity;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRootChildEntity(): ?ChildEntity
    {
        return $this->rootChildEntity;
    }

    public function setRootChildEntity(?ChildEntity $rootChildEntity): self
    {
        $this->rootChildEntity = $rootChildEntity;

        return $this;
    }
}
</code>```

<?php

namespace App\Entity;

use App\Repository\ChildEntityRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class ChildEntity
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\ManyToOne(targetEntity: ParentEntity::class)]
    #[ORM\JoinColumn(nullable: false)]
    private $parentEntity;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getParentEntity(): ?ParentEntity
    {
        return $this->parentEntity;
    }

    public function setParentEntity(?ParentEntity $parentEntity): self
    {
        $this->parentEntity = $parentEntity;

        return $this;
    }
}
```
<p>which generates the following SQL:</p>
```doctrine.DEBUG: CREATE SEQUENCE child_entity_id_seq INCREMENT BY 1 MINVALUE 1 START 1 [] []
doctrine.DEBUG: CREATE SEQUENCE parent_entity_id_seq INCREMENT BY 1 MINVALUE 1 START 1 [] []
doctrine.DEBUG: CREATE TABLE child_entity (id INT NOT NULL, parent_entity_id INT NOT NULL, PRIMARY KEY(id)) [] []
doctrine.DEBUG: CREATE INDEX IDX_677D8034706E52B3 ON child_entity (parent_entity_id) [] []
doctrine.DEBUG: CREATE TABLE parent_entity (id INT NOT NULL, root_child_entity_id INT NOT NULL, PRIMARY KEY(id)) [] []
doctrine.DEBUG: CREATE INDEX IDX_413B87AEE5B68E27 ON parent_entity (root_child_entity_id) [] []
doctrine.DEBUG: ALTER TABLE child_entity ADD CONSTRAINT FK_677D8034706E52B3 FOREIGN KEY (parent_entity_id) REFERENCES parent_entity (id) NOT DEFERRABLE INITIALLY IMMEDIATE [] []
doctrine.DEBUG: ALTER TABLE parent_entity ADD CONSTRAINT FK_413B87AEE5B68E27 FOREIGN KEY (root_child_entity_id) REFERENCES child_entity (id) NOT DEFERRABLE INITIALLY IMMEDIATE [] []
```

答:
Circular entities with all IDs defined as not-nullable are impossible to persist sequentionally when immediate consistency is enforced. This is by default in almost every DB vendor.

So firstly you need to defer the consistency - see http://dbadailystuff.com/deferred-constraints-in-postgresql . For PostgreSQL and Doctrine ORM specifically, this can you fixed by specifying deferrable option for the foreign key, see https://github.com/doctrine/dbal/blob/e839cecc812fd04ec6c39fc865302b6a322d967d/src/Platforms/PostgreSQLPlatform.php#L439 .

and secondly you need to convince Doctrine ORM to insert the parent row with the ID of the child row. I doubt there is a direct support because the 1st point is very inconsistent across DB vendors, but feel free to open a ticket at https://github.com/doctrine/orm/issues , the authors may advice you how to enforce Doctrine ORM to insert the child ID immediately at least.

Body:
I have two entities that reference each other and have not null constraints, and am trying to persist them with the following script:

$parentEntity = new \App\Entity\ParentEntity();
$childEntity = new \App\Entity\ChildEntity();
$childEntity->setParentEntity($parentEntity);
$parentEntity->setRootChildEntity($childEntity);

$this->entityManager->persist($parentEntity);
$this->entityManager->persist($childEntity);

printf('$parentEntity->getId(): %s'.PHP_EOL, $parentEntity->getId());
printf('$childEntity->getId(): %s'.PHP_EOL, $childEntity->getId());
printf('$parentEntity->getRootChildEntity()->getId(): %s'.PHP_EOL, $parentEntity->getRootChildEntity()->getId());
printf('$childEntity->getParentEntity()->getId(): %s'.PHP_EOL, $childEntity->getParentEntity()->getId());

$this->entityManager->flush();

When executing the script, both entities are populated with integer IDs after being persisted (obtained by the SELECT NEXTVAL queries), but when flushed, instead NULL is used and I get a not null violation.

If I was just getting a foreign key constraint, I would understand why and I could get around it by making the constraints deferrable or bypassing them by temporarily disabling triggers.

But not so with a null violation.  Why is this happening? Without removing the not null constraint which I wish to keep, is there a way around it?

doctrine.DEBUG: SELECT NEXTVAL('parent_entity_id_seq') [] []
doctrine.DEBUG: SELECT NEXTVAL('child_entity_id_seq') [] []

$parentEntity->getId(): 1
$childEntity->getId(): 1
$parentEntity->getRootChildEntity()->getId(): 1
$childEntity->getParentEntity()->getId(): 1

doctrine.DEBUG: "START TRANSACTION" [] []
doctrine.DEBUG: INSERT INTO parent_entity (id, root_child_entity_id) VALUES (?, ?) {"1":1,"2":null} []
doctrine.DEBUG: "ROLLBACK" [] []
console.CRITICAL: Error thrown while running command "app:add-tenant". Message: "An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "root_child_entity_id" of relation "parent_entity" violates not-null constraint DETAIL:  Failing row contains (1, null)." {"exception":"[object] (Doctrine\\DBAL\\Exception\\NotNullConstraintViolationException(code: 7): An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null). at /srv/api/vendor/doctrine/dbal/src/Driver/API/PostgreSQL/ExceptionConverter.php:51)\n[previous exception] [object] (Doctrine\\DBAL\\Driver\\PDO\\Exception(code: 7): SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null). at /srv/api/vendor/doctrine/dbal/src/Driver/PDO/Exception.php:26)\n[previous exception] [object] (PDOException(code: 23502): SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null). at /srv/api/vendor/doctrine/dbal/src/Driver/PDO/Statement.php:101)","command":"app:add-tenant","message":"An exception occurred while executing a query: SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"root_child_entity_id\" of relation \"parent_entity\" violates not-null constraint\nDETAIL:  Failing row contains (1, null)."} []

My entities:

<?php

namespace App\Entity;

use App\Repository\ParentEntityRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class ParentEntity
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\ManyToOne(targetEntity: ChildEntity::class)]
    #[ORM\JoinColumn(nullable: false)]
    private $rootChildEntity;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRootChildEntity(): ?ChildEntity
    {
        return $this->rootChildEntity;
    }

    public function setRootChildEntity(?ChildEntity $rootChildEntity): self
    {
        $this->rootChildEntity = $rootChildEntity;

        return $this;
    }
}

<?php

namespace App\Entity;

use App\Repository\ChildEntityRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class ChildEntity
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\ManyToOne(targetEntity: ParentEntity::class)]
    #[ORM\JoinColumn(nullable: false)]
    private $parentEntity;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getParentEntity(): ?ParentEntity
    {
        return $this->parentEntity;
    }

    public function setParentEntity(?ParentEntity $parentEntity): self
    {
        $this->parentEntity = $parentEntity;

        return $this;
    }
}

which generates the following SQL:

doctrine.DEBUG: CREATE SEQUENCE child_entity_id_seq INCREMENT BY 1 MINVALUE 1 START 1 [] []
doctrine.DEBUG: CREATE SEQUENCE parent_entity_id_seq INCREMENT BY 1 MINVALUE 1 START 1 [] []
doctrine.DEBUG: CREATE TABLE child_entity (id INT NOT NULL, parent_entity_id INT NOT NULL, PRIMARY KEY(id)) [] []
doctrine.DEBUG: CREATE INDEX IDX_677D8034706E52B3 ON child_entity (parent_entity_id) [] []
doctrine.DEBUG: CREATE TABLE parent_entity (id INT NOT NULL, root_child_entity_id INT NOT NULL, PRIMARY KEY(id)) [] []
doctrine.DEBUG: CREATE INDEX IDX_413B87AEE5B68E27 ON parent_entity (root_child_entity_id) [] []
doctrine.DEBUG: ALTER TABLE child_entity ADD CONSTRAINT FK_677D8034706E52B3 FOREIGN KEY (parent_entity_id) REFERENCES parent_entity (id) NOT DEFERRABLE INITIALLY IMMEDIATE [] []
doctrine.DEBUG: ALTER TABLE parent_entity ADD CONSTRAINT FK_413B87AEE5B68E27 FOREIGN KEY (root_child_entity_id) REFERENCES child_entity (id) NOT DEFERRABLE INITIALLY IMMEDIATE [] []


来源: stackexchange

问:
Dart: How to sort the lists into the object tree
I have an array with a bunch of objects, where there are parentId and id parameters, how do I make a tree of nested objects, sort so that the first object is an object without parentId, and the rest are nested in it in the children field.

For example:

```<code>{
"id": 1,
"parentId": null,
"children": [
    {
      "id": 2,
      "parentId": 1,
      "children": [
        "id": 3,
        "parentId": 2,
        "children": [...]
      ] ...
    }
  ]
}
</code>```

https://dartpad.dev/?id=799b87806e56d036ba0dac7c9bebcbb2

答:
I worked on your dartpad, I couldn't find any issues, but if you do, please let me know! The resulting code looks like this:

List<Object1> objects = [
  Object1(id: 1, parentId: null),
  Object1(id: 2, parentId: 1),
  Object1(id: 3, parentId: 2),
  Object1(id: 4, parentId: 2),
  Object1(id: 5, parentId: 2),
  Object1(id: 6, parentId: 1),
  Object1(id: 7, parentId: 6),
  Object1(id: 8, parentId: 6),
  Object1(id: 9, parentId: 7),
  Object1(id: 10, parentId: 9),
  Object1(id: 11, parentId: 9),
  Object1(id: 12, parentId: 10),
];

class Object1 {
  Object1({
    required this.id,
    this.parent,
    this.parentId,
  });

  Object1? parent;
  final List<Object1> children = [];

  int id;
  int? parentId;

  void addChildren(List<Object1> list) {
    final newList = getChildren(list, id);
    for (final object in newList) {
      object.parent = this;
      object.addChildren(list);
      children.add(object);
    }
  }

  @override
  String toString() {
    return 'Object1('
      'id: $id,\n'
      'parentId: $parentId,\n'
      'children: ${children.toString()}'
      ')';
  }
}

void main() {
  Object1? main;
  for (final object in objects) {
    if (object.parentId == null) {
      main = object;
      break;
    }
  }
  if (main != null) {
    main.addChildren(objects);
    print(main.toString());
  }
}

List<Object1> getChildren(List<Object1> list, int id) {
  final List<Object1> newList = [];
  for (final object in list) {
    if (object.parentId == id) {
      newList.add(object);
    }
  }
  return newList;
}
```

ContentLicense: CC BY-SA 4.0

Body:
I have an array with a bunch of objects, where there are parentId and id parameters, how do I make a tree of nested objects, sort so that the first object is an object without parentId, and the rest are nested in it in the children field.

For example:

{
"id": 1,
"parentId": null,
"children": [
    {
      "id": 2,
      "parentId": 1,
      "children": [
        "id": 3,
        "parentId": 2,
        "children": [...]
      ] ...
    }
  ]
}

https://dartpad.dev/?id=799b87806e56d036ba0dac7c9bebcbb2


问:
mule 3 XPR to dataweave 2.0 migration
In my case, I'm doing a migration from Mule 3 to Mule 4.

In Mule 4, xpr files are not supported for xml transformation.

So I converted the xpr file to dataweave 2.0.

Most of the logic was solved,but i don't know how to updated the DTOSteps value and DTOCoverage.@FullTermAmt = fullTermAmts.

mule 3 XPR: https://github.com/Manikandan99/XPR_conversion/blob/master/responseCISGExposure.xpr

My Mule 4 Application:https://github.com/Manikandan99/XPR_conversion/tree/master/xpr_validation

Input xml Request: https://github.com/Manikandan99/XPR_conversion/blob/master/xml_request.xml

Expected output xml response: https://github.com/Manikandan99/XPR_conversion/blob/master/responseCISGExposure.xpr

I've defined all the variables in the Mule  4 application.

Stackoverflow not allow me to post many lines of code, so i provided the github links. please go through it.

Please help me to solve it.

答:
I updated the dataweave code in my mule 4 based on xpr file logic.

For auto increment, I've used the AtomicInteger and the inbuilt incrementAndGet() function in dataweave 2.0.

I added a dependency to my pom.xml:

```<code><dependency>
<groupId>org.mule.module</groupId>
<artifactId>mule-java-module</artifactId>
<version>1.2.5</version>
<classifier>mule-plugin</classifier>
</dependency>
</code>```

My dataweave 2.0 code:

```<code>%dw 2.0
import java!java::util::concurrent::atomic::AtomicInteger
var processFlag = 0
var stepOrder = 1
var subStepOrder = 1
var subSubStepOrder = 1
var multiChar = "X"
var coverageCd = "LIAB"
var fullTermAmts = vars.CISGOutput.Premium.FinalLiabPrem.Exposure.LIAB
var startingValue = AtomicInteger::new(0)
var instartingValue = AtomicInteger::new(0)
output application/xml
fun soutincrement() = Java::invoke('java.util.concurrent.atomic.AtomicInteger', 'incrementAndGet()', startingValue, {})
fun sinincrement() = Java::invoke('java.util.concurrent.atomic.AtomicInteger', 'incrementAndGet()', instartingValue, {})
fun transformSteps(x, index)=
    x filterObject ($$ as String != "DTOSteps") ++
    {
                    DTOSteps: transformNewSteps()

    }
fun transformNewSteps()=
    {
        DTOStep @(Order:soutincrement(), Name:"Base Premium", Operation:"=", Factor: vars.CISGOutput.Factors.LIAB.BasePrem, Value: vars.CISGOutput.Factors.LIAB.BasePrem): DTOSteps: transformChildSteps(),
        DTOStep @(Order:soutincrement(), Name:"Large Premium Discount Plan", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.LPDP, Value: vars.CISGOutput.Factors.LIAB.LPDP): null,
        DTOStep @(Order:soutincrement(), Name:"IRPM", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.IRPM, Value: vars.CISGOutput.Factors.LIAB.IRPM): null,
        DTOStep @(Order:soutincrement(), Name:"Term Factor", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.Term, Value: vars.CISGOutput.Factors.LIAB.Term): null
    }
fun transformChildSteps()=
    {
        DTOStep @(Order:sinincrement(), Name:"Exposure", Operation:"=", Factor: vars.CISGOutput.Factors.LIAB.Exposure, Value: vars.CISGOutput.Factors.LIAB.Exposure): null,
        DTOStep @(Order:sinincrement(), Name:"Base Rate", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.BaseRate, Value: vars.CISGOutput.Factors.LIAB.BaseRate): null,
        DTOStep @(Order:sinincrement(), Name:"Territory", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.Terr, Value: vars.CISGOutput.Factors.LIAB.Terr): null,
        DTOStep @(Order:sinincrement(), Name:"ILF", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.Limit, Value: vars.CISGOutput.Factors.LIAB.Limit): null,
        DTOStep @(Order:sinincrement(), Name:"Med Pay", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.MedPay, Value: vars.CISGOutput.Factors.LIAB.BasePrem): null
    }

fun transformCoverage(x, index)=
    x match {
      case is Object -> x mapObject
        if ($$ as String == "DTOCoverage" and $$.@CoverageCd == "LIAB")
            {
                DTOCoverage @(( $$.@ - "FullTermAmt" ), FullTermAmt: fullTermAmts):
                    transformSteps($, index)
            }
        else
            (($$): transformCoverage($, index+1))
      else -> $
    }
---
transformCoverage(payload,1)
</code>```

Its work's but its not optimized well.

Hope it helpful for some how doing migration on xpr to dataweave.

Title: mule 3 XPR to dataweave 2.0 migration

Body:
I updated the dataweave code in my mule 4 based on xpr file logic.

For auto increment, I've used the AtomicInteger and the inbuilt incrementAndGet() function in dataweave 2.0.

I added a dependency to my pom.xml:

<dependency>
<groupId>org.mule.module</groupId>
<artifactId>mule-java-module</artifactId>
<version>1.2.5</version>
<classifier>mule-plugin</classifier>
</dependency>

My dataweave 2.0 code:

%dw 2.0
import java!java::util::concurrent::atomic::AtomicInteger
var processFlag = 0
var stepOrder = 1
var subStepOrder = 1
var subSubStepOrder = 1
var multiChar = "X"
var coverageCd = "LIAB"
var fullTermAmts = vars.CISGOutput.Premium.FinalLiabPrem.Exposure.LIAB
var startingValue = AtomicInteger::new(0)
var instartingValue = AtomicInteger::new(0)
output application/xml
fun soutincrement() = Java::invoke('java.util.concurrent.atomic.AtomicInteger', 'incrementAndGet()', startingValue, {})
fun sinincrement() = Java::invoke('java.util.concurrent.atomic.AtomicInteger', 'incrementAndGet()', instartingValue, {})
fun transformSteps(x, index)=
    x filterObject ($$ as String != "DTOSteps") ++
    {
                    DTOSteps: transformNewSteps()

    }
fun transformNewSteps()=
    {
        DTOStep @(Order:soutincrement(), Name:"Base Premium", Operation:"=", Factor: vars.CISGOutput.Factors.LIAB.BasePrem, Value: vars.CISGOutput.Factors.LIAB.BasePrem): DTOSteps: transformChildSteps(),
        DTOStep @(Order:soutincrement(), Name:"Large Premium Discount Plan", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.LPDP, Value: vars.CISGOutput.Factors.LIAB.LPDP): null,
        DTOStep @(Order:soutincrement(), Name:"IRPM", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.IRPM, Value: vars.CISGOutput.Factors.LIAB.IRPM): null,
        DTOStep @(Order:soutincrement(), Name:"Term Factor", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.Term, Value: vars.CISGOutput.Factors.LIAB.Term): null
    }
fun transformChildSteps()=
    {
        DTOStep @(Order:sinincrement(), Name:"Exposure", Operation:"=", Factor: vars.CISGOutput.Factors.LIAB.Exposure, Value: vars.CISGOutput.Factors.LIAB.Exposure): null,
        DTOStep @(Order:sinincrement(), Name:"Base Rate", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.BaseRate, Value: vars.CISGOutput.Factors.LIAB.BaseRate): null,
        DTOStep @(Order:sinincrement(), Name:"Territory", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.Terr, Value: vars.CISGOutput.Factors.LIAB.Terr): null,
        DTOStep @(Order:sinincrement(), Name:"ILF", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.Limit, Value: vars.CISGOutput.Factors.LIAB.Limit): null,
        DTOStep @(Order:sinincrement(), Name:"Med Pay", Operation:multiChar, Factor: vars.CISGOutput.Factors.LIAB.MedPay, Value: vars.CISGOutput.Factors.LIAB.BasePrem): null
    }

fun transformCoverage(x, index)=
    x match {
      case is Object -> x mapObject
        if ($$ as String == "DTOCoverage" and $$.@CoverageCd == "LIAB")
            {
                DTOCoverage @(( $$.@ - "FullTermAmt" ), FullTermAmt: fullTermAmts):
                    transformSteps($, index)
            }
        else
            (($$): transformCoverage($, index+1))
      else -> $
    }
---
transformCoverage(payload,1)

Its work's but its not optimized well.

Hope it helpful for some how doing migration on xpr to dataweave.


问:
Initiating objects with mutual dependency
I'm trying to model entities from a film database. I have films which have a list of directors and directors which have a list of films. Objects I made are like this:

```<code>public class eFilm
{
    //Basic properties
    public int ID { get; private set; }
    public string Title { get; set; }
    public DateTime? Date { get; set; }

    public List<eDirector> Directors = new List<eDirector>();
    public List<eActor> Actors = new List<eActor>();
    public eMedia_Type Type;

    /// <summary>
    /// Initiate a new Films from Films_Data object
    /// </summary>
    /// <param name="Film">Films_Data object from which to initiate a new film</param>
    public eFilm(Film Film)
    {
        this.ID = Film.ID;
        this.Title = Film.Title;
        this.Date = Film.Date;
        this.Synopsis = Film.Synopsis;

        //Add directors
        Film.Films_Directors.Select(fd => fd.Director).ToList<Director>().ForEach(d => this.Directors.Add(new eDirector(d)));
        //Add actors
        Film.Films_Actors.Select(fa => fa.Actor).ToList<Actor>().ForEach(a => this.Actors.Add(new eActor(a)));
        //Add type
        this.Type = new eMedia_Type(Film.Media_Type);
    }
}

public class eDirector
{
    public int ID { get; private set; }
    public string Name{ get; set;}

    public List<eFilm> Films = new List<eFilm>();

    public eDirector(Director Director)
    {
        this.ID = Director.ID;
        this._Name = Director.Name;

        _Number_Of_Films = Director.Films_Directors.Select(d => d.Film).ToList<Film>().ForEach(f => this.Films.Add(new eFilm(f)));
    }
}
</code>```

I've omitted some stuff for brevity. This gives me a stack overflow because I add directors to films which then adds films to directors which adds directors to films etc.
I can't figure out a way to model this, but there obviously must be some way to do this since the entity framework can...

Any advice on how to proceed would be much appreciated.

EDIT: Some info that might be needed. I am doing this to add a layer on top of the classes generated by Linq-to-SQL, to enable me to perform some checks on data before I pass it to the repository for persistence. I am using c# and ASP.NET MVC.

答:
What you've done is an unlimited loop, films adding directors which adds films until it throws a StackOverflowException, the reason why entity framework "can" do this is because by default entity framework is doing what is called lazy loading, which means that when you access the list of directors it makes a call to the database and gets them, the way your entities are now however they will eager load since the virtual keyword is used to have entity framework do lazy loading.

My suggestion would be that if you want to imitate the behavior of entity framework is to do something like this:

```<code>public class Film {
    ...
    public readonly IEnumerable<Director> Directors = _repository.GetDirectors(this.iD);
}
</code>```

you would then add a similar property in the Director class, this way you get the data only when you need it and it won't do an infinite loop in order to eager load everything.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to model entities from a film database. I have films which have a list of directors and directors which have a list of films. Objects I made are like this:

public class eFilm
{
    //Basic properties
    public int ID { get; private set; }
    public string Title { get; set; }
    public DateTime? Date { get; set; }

    public List<eDirector> Directors = new List<eDirector>();
    public List<eActor> Actors = new List<eActor>();
    public eMedia_Type Type;

    ///
    /// Initiate a new Films from Films_Data object
    ///
    /// <param name="Film">Films_Data object from which to initiate a new film</param>
    public eFilm(Film Film)
    {
        this.ID = Film.ID;
        this.Title = Film.Title;
        this.Date = Film.Date;
        this.Synopsis = Film.Synopsis;

        //Add directors
        Film.Films_Directors.Select(fd => fd.Director).ToList<Director>().ForEach(d => this.Directors.Add(new eDirector(d)));
        //Add actors
        Film.Films_Actors.Select(fa => fa.Actor).ToList<Actor>().ForEach(a => this.Actors.Add(new eActor(a)));
        //Add type
        this.Type = new eMedia_Type(Film.Media_Type);
    }
}

public class eDirector
{
    public int ID { get; private set; }
    public string Name{ get; set;}

    public List<eFilm> Films = new List<eFilm>();

    public eDirector(Director Director)
    {
        this.ID = Director.ID;
        this._Name = Director.Name;

        _Number_Of_Films = Director.Films_Directors.Select(d => d.Film).ToList<Film>().ForEach(f => this.Films.Add(new eFilm(f)));
    }
}

I've omitted some stuff for brevity. This gives me a stack overflow because I add directors to films which then adds films to directors which adds directors to films etc.
I can't figure out a way to model this, but there obviously must be some way to do this since the entity framework can...

Any advice on how to proceed would be much appreciated.

EDIT: Some info that might be needed. I am doing this to add a layer on top of the classes generated by Linq-to-SQL, to enable me to perform some checks on data before I pass it to the repository for persistence. I am using c# and ASP.NET MVC.

Body:
What you've done is an unlimited loop, films adding directors which adds films until it throws a StackOverflowException, the reason why entity framework "can" do this is because by default entity framework is doing what is called lazy loading, which means that when you access the list of directors it makes a call to the database and gets them, the way your entities are now however they will eager load since the virtual keyword is used to have entity framework do lazy loading.

My suggestion would be that if you want to imitate the behavior of entity framework is to do something like this:

public class Film {
    ...
    public readonly IEnumerable<Director> Directors = _repository.GetDirectors(this.iD);
}

you would then add a similar property in the Director class, this way you get the data only when you need it and it won't do an infinite loop in order to eager load everything.


问:
Updating an XML with a list of changes
I have an XML

```<code>var xxx = new XDocument(new XElement("Log",
new XElement("Set", new XAttribute("id", 1), new XElement("File", new XAttribute("path", "path1"))),
new XElement("Set", new XAttribute("id", 2), new XElement("File", new XAttribute("path", "path2"))),
new XElement("Set", new XAttribute("id", 3), new XElement("File", new XAttribute("path", "path3")))
));

<Log>
    <Set id = 1>
        <File path = "path1">
    </Set>
    <Set id = 2>
        <File path = "path2">
    </Set>
    <Set id = 3>
        <File path = "path3">
    </Set>
</Log>
</code>```

and a List of changes

```<code>var sets = new[] { new { id = 4, Path = "path4" }, new { id = 5, Path = "path2" } }.ToList();
</code>```

I want to update XML with a list by "path" attribute: remove "set" elements with path not in list, not to touch existed paths and add new ones. Actually parse list into new XML but keep old ids (and other attributes in real task).

The result should be

```<code><Log>
    <Set id = 2>
        <File path = "path2">
    </Set>
    <Set id = 4>
        <File path = "path4">
    </Set>
</Log>
</code>```

I can do it with loops but how to do it with LINQ?

答:
Just replace the children with the new elements, since you're so keen on not using a loop.</p>
```<code>xxx.Root.ReplaceAll(
    sets.Select(x =>
        new XElement("Set",
            new XAttribute("id", x.id),
            new XElement("File",
                new XAttribute("path", x.Path)
            )
        )
    )
);

</code>```

Title: Updating an XML with a list of changes

Body:
I have an XML

var xxx = new XDocument(new XElement("Log",
new XElement("Set", new XAttribute("id", 1), new XElement("File", new XAttribute("path", "path1"))),
new XElement("Set", new XAttribute("id", 2), new XElement("File", new XAttribute("path", "path2"))),
new XElement("Set", new XAttribute("id", 3), new XElement("File", new XAttribute("path", "path3")))
));

<Log>
    <Set id = 1>
        <File path = "path1">
    </Set>
    <Set id = 2>
        <File path = "path2">
    </Set>
    <Set id = 3>
        <File path = "path3">
    </Set>
</Log>

and a List of changes

var sets = new[] { new { id = 4, Path = "path4" }, new { id = 5, Path = "path2" } }.ToList();

I want to update XML with a list by "path" attribute: remove "set" elements with path not in list, not to touch existed paths and add new ones. Actually parse list into new XML but keep old ids (and other attributes in real task).

The result should be

<Log>
    <Set id = 2>
        <File path = "path2">
    </Set>
    <Set id = 4>
        <File path = "path4">
    </Set>
</Log>

I can do it with loops but how to do it with LINQ?

Body:
Just replace the children with the new elements, since you're so keen on not using a loop.

xxx.Root.ReplaceAll(
    sets.Select(x =>
        new XElement("Set",
            new XAttribute("id", x.id),
            new XElement("File",
                new XAttribute("path", x.Path)
            )
        )
    )
);


问:
Argument of type 'string' is not assignable to parameter of type... (React Hook Form) (TypeScript)
I have typescript interface with answers:

```<code>interface IAnswers { answer1: string; answer2: string ... }
</code>```

and want to set value using react hook form:

```<code>setValue(`answer${data.id}`, 'Answer value')
</code>```

data.id is number with question id, but i got

```<code>Argument of type 'string' is not assignable to parameter of type '"answer1" | "answer2" | "answer3"...
</code>```

答:
Could you try like this;</p>
```<code>import React from 'react'

interface IAnswers {
    answer1?: string,
    answer2?: string,
}

const TestComponent = () => {

    const [answers, setAnswers] = React.useState<IAnswers>({});

    const addAnswer = (id: string | number, value: string) => {

        const key = `answer${id}`;

        setAnswers({
            ...answers,
            [key]: value
        })

    }

    return (
        <div>

        </div>
    )
}

export default TestComponent
</code>```

Body:
I have typescript interface with answers:

interface IAnswers { answer1: string; answer2: string ... }

and want to set value using react hook form:

setValue(`answer${data.id}`, 'Answer value')

data.id is number with question id, but i got

Argument of type 'string' is not assignable to parameter of type '"answer1" | "answer2" | "answer3"...

Body:
Could you try like this;

import React from 'react'

interface IAnswers {
    answer1?: string,
    answer2?: string,
}

const TestComponent = () => {

    const [answers, setAnswers] = React.useState<IAnswers>({});

    const addAnswer = (id: string | number, value: string) => {

        const key = `answer${id}`;

        setAnswers({
            ...answers,
            [key]: value
        })

    }

    return (
        <div>

        </div>
    )
}

export default TestComponent


问:
How to write testcases using Xunit test for extension method like Any
Actually this is my service layer. I want to test a create account method by Xunit testing. How can I proceed further?

public class UserService :IUserService // service
{

    #region Property
    private readonly IAppDbContext _appDbContext;
    #endregion

    #region Constructor
    public UserService(IAppDbContext appDbContext)
    {
        _appDbContext = appDbContext;
    }
     #endregion

    public int Create(User model)
    {
        _appDbContext.Users.Add(model);
        _appDbContext.SaveChanges();

        return model.Id;
    }

    public  bool CheckAccount(User data)
    {

            if (this._appDbContext.Users.Any(x => x.UserName == data.UserName))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public string CheckDetails(User data)
        {
            if (this._appDbContext.Users.Any(x => x.Password == data.Password) &&
                this._appDbContext.Users.Any(x => x.UserName == data.UserName))
            {
                var userid = "";
                var obj = this._appDbContext.Users.Where(x => x.UserName == data.UserName);
                foreach (var i in obj)
                {
                    userid = i.Id.ToString();
                }

                return userid;
            }
            else
            {

                return null;
            }
        }
    }
}
```

Please tell ,how to I test this method are there in User service by xunit testing

答:
That's simple. You need to use [Theory] and [InlineData] XUnit attributes.
I prepared a small example for you

```<code>public class UnitTest
{
    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    [Theory]
    [InlineData("First")]
    public void Test1(string productName)
    {
        var productList = new List<Product>
        {
            new()
            {
                Id = 1,
                Name = "First"
            },
            new()
            {
                Id = 2,
                Name = "Second"
            }
        };

        Assert.True(productList.Any(product => product.Name == productName));
    }
}
</code>```

Body:
Actually this is my service layer. I want to test a create account method by Xunit testing. How can I proceed further?

public class UserService :IUserService // service
{

    #region Property
    private readonly IAppDbContext _appDbContext;
    #endregion

    #region Constructor
    public UserService(IAppDbContext appDbContext)
    {
        _appDbContext = appDbContext;
    }
     #endregion

    public int Create(User model)
    {
        _appDbContext.Users.Add(model);
        _appDbContext.SaveChanges();

        return model.Id;
    }

    public  bool CheckAccount(User data)
    {

            if (this._appDbContext.Users.Any(x => x.UserName == data.UserName))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public string CheckDetails(User data)
        {
            if (this._appDbContext.Users.Any(x => x.Password == data.Password) &&
                this._appDbContext.Users.Any(x => x.UserName == data.UserName))
            {
                var userid = "";
                var obj = this._appDbContext.Users.Where(x => x.UserName == data.UserName);
                foreach (var i in obj)
                {
                    userid = i.Id.ToString();
                }

                return userid;
            }
            else
            {

                return null;
            }
        }
    }
}

Please tell ,how to I test this method are there in User service by xunit testing

Body:
That's simple. You need to use [Theory] and [InlineData] XUnit attributes.
I prepared a small example for you

public class UnitTest
{
    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    [Theory]
    [InlineData("First")]
    public void Test1(string productName)
    {
        var productList = new List<Product>
        {
            new()
            {
                Id = 1,
                Name = "First"
            },
            new()
            {
                Id = 2,
                Name = "Second"
            }
        };

        Assert.True(productList.Any(product => product.Name == productName));
    }
}


问:
element attributes missing when parsing XML with iterparse/lxml/python 2
Here's my use case:
I have a potentially large XML file, and I want to output the frequency of all the unique structural variations of a given element type. Element attributes should be included as part of the uniqueness test. The output should sort the variations by frequency.

Here's a trivial input example, with 4 entries for automobile:

```<code><automobile>
    <mileage>20192</mileage>
    <year>2005</year>
    <user_defined name="color">red</user_defined>
</automobile>
<automobile>
    <mileage>1098</mileage>
    <year>2018</year>
    <user_defined name="color">blue</user_defined>
</automobile>
<automobile>
    <mileage>17964</mileage>
    <year>2012</year>
    <user_defined name="title_status">salvage</user_defined>
</automobile>
<automobile>
    <mileage>198026</mileage>
    <year>1990</year>
</automobile>
</code>```

The output I expect would look like this:

```<code><automobile automobile_frequency="2">
    <mileage />
    <year />
    <user_defined name="color" />
</automobile>
<automobile automobile_frequency="1">
    <mileage />
    <year />
    <user_defined name="title_status" />
</automobile>
<automobile automobile_frequency="1">
    <mileage />
    <year />
</automobile>
</code>```

I've implemented the code using iterparse, but when it's processing the elements, the attributes do not exist in the element. The code logic appears to be correct, but attributes simply don't exist; they are not written in the output, and they are not present for the uniqueness test. Per the above input example, this is what I get on output:

```<code><root>
  <automobile automobile_frequency="3">
    <mileage/>
    <year/>
    <user_defined/>
  </automobile>
  <automobile automobile_frequency="1">
    <mileage/>
    <year/>
  </automobile>
</root>
</code>```

The usage is:

```<code>xplore.py input.xml node_to_explore
</code>```

In the above example, I used:

```<code>xplore.py trivial.xml automobile
</code>```

Here's the source:

```<code>from lxml import etree
import sys
import re
from datetime import datetime

# global node signature map
structure_map = {}
# global code frequency map
frequency_map = {}
# output tree
tmp_root = etree.Element("tmp_root")

def process_element(el):
    global target
    if el.tag != target:
        return
    # get the structure of the element
    structure = get_structure(el)
    global structure_map
    structure_key = etree.tostring(structure, pretty_print=True)
    if structure_key not in structure_map.keys():
        # add signature to structure map
        structure_map[structure_key] = structure
        # add node to output
        global tmp_root
        tmp_root.append(structure)
        # add signature to frequency map
        frequency_map[structure_key] = 1
    else:
        # increment frequency map
        frequency_map[structure_key] += 1

# returns a unique string representing the structure of the node
# including attributes
def get_structure(el):
    # create new element for the return value
    ret = etree.Element(el.tag)
    # get attributes
    attribute_keys = el.attrib.keys()
    for attribute_key in attribute_keys:
        ret.set(attribute_key, el.get(attribute_key))
    # check for children
    children = list(el)
    for child in children:
        ret.append(get_structure(child))
    return ret

if len(sys.argv) < 3:
    print "Must specify an XML file for processing, as well as an element type!"
    exit(0)

# Get XML file
xml = sys.argv[1]
# Get output file name
output_file = xml[0:xml.rindex(".")]+".txt"
# get target element type to evaluate
target = sys.argv[2]
# mark start
startTime = datetime.now()
# Parse XML

print '==========================='
print 'Parsing XML'
print '==========================='
context = etree.iterparse(xml, events=('end',))
for event, element in context:
    process_element(element)
    element.clear()
# create tree sorted by frequency
ranked = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True)
root = etree.Element("root")
for item in ranked:
    structure = structure_map[item[0]]
    structure.set(target+"_frequency", str(item[1]))
    root.append(structure)
# pretty print root
out = open(output_file, 'w')
out.write(etree.tostring(root, pretty_print=True))
# output run time
time = datetime.now() - startTime
reg3 = re.compile("\\d+:\\d(\\d:\\d+\\.\\d{4})")
time = re.search(reg3, unicode(time))
time = "Runtime: %ss" % (time.group(1).encode("utf-8"))
print(time)
</code>```

In the debugger, I can clearly see that the attributes are missing from elements in the calls to get_structure. Can anyone tell me why this is the case?

答:
The data:

<root>
    <automobile>
        <mileage>20192</mileage>
        <year>2005</year>
        <user_defined name="color">red</user_defined>
    </automobile>
    <automobile>
        <mileage>1098</mileage>
        <year>2018</year>
        <user_defined name="color">blue</user_defined>
    </automobile>
    <automobile>
        <mileage>17964</mileage>
        <year>2012</year>
        <user_defined name="title_status">salvage</user_defined>
    </automobile>
    <automobile>
        <mileage>198026</mileage>
        <year>1990</year>
    </automobile>
</root>
```
<p>The code:</p>
<pre class="lang-py prettyprint-override"><code>from lxml import etree
import sys
import re
from datetime import datetime

# global node signature map
structure_map = {}
# global code frequency map
frequency_map = {}
# output tree
tmp_root = etree.Element("tmp_root")

def process_element(el):
    # get the structure of the element
    structure = get_structure(el)
    global structure_map
    structure_key = etree.tostring(structure, pretty_print=True)
    if structure_key not in structure_map.keys():
        # add signature to structure map
        structure_map[structure_key] = structure
        # add node to output
        global tmp_root
        tmp_root.append(structure)
        # add signature to frequency map
        frequency_map[structure_key] = 1
    else:
        # increment frequency map
        frequency_map[structure_key] += 1

# returns a unique string representing the structure of the node
# including attributes
def get_structure(el):
    # create new element for the return value
    ret = etree.Element(el.tag)
    # get attributes
    attribute_keys = el.attrib.keys()
    for attribute_key in attribute_keys:
        ret.set(attribute_key, el.get(attribute_key))
    # check for children
    children = list(el)
    for child in children:
        ret.append(get_structure(child))
    return ret

if len(sys.argv) < 3:
    print "Must specify an XML file for processing, as well as an element type!"
    exit(0)

# Get XML file
xml = sys.argv[1]
# Get output file name
output_file = xml[0:xml.rindex(".")]+".txt"
# get target element type to evaluate
target = sys.argv[2]
# mark start
startTime = datetime.now()
# Parse XML

print '==========================='
print 'Parsing XML'
print '==========================='
context = etree.iterparse(xml, events=('end',))
element_to_clear = []
for event, element in context:
    element_to_clear.append(element)
    global target
    if element.tag == target:
        process_element(element)
        for ele in element_to_clear:
            ele.clear()
        element_to_clear = []
# create tree sorted by frequency
ranked = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True)
root = etree.Element("root")
for item in ranked:
    structure = structure_map[item[0]]
    structure.set(target+"_frequency", str(item[1]))
    root.append(structure)
# pretty print root
out = open(output_file, 'w')
out.write(etree.tostring(root, pretty_print=True))
# output run time
time = datetime.now() - startTime
reg3 = re.compile("\\d+:\\d(\\d:\\d+\\.\\d{4})")
time = re.search(reg3, unicode(time))
time = "Runtime: %ss" % (time.group(1).encode("utf-8"))
print(time)
</code>```

The command: xplore.py trivial.xml automobile

Body:
Here's my use case:
I have a potentially large XML file, and I want to output the frequency of all the unique structural variations of a given element type. Element attributes should be included as part of the uniqueness test. The output should sort the variations by frequency.

Here's a trivial input example, with 4 entries for automobile:

<automobile>
    <mileage>20192</mileage>
    <year>2005</year>
    <user_defined name="color">red</user_defined>
</automobile>
<automobile>
    <mileage>1098</mileage>
    <year>2018</year>
    <user_defined name="color">blue</user_defined>
</automobile>
<automobile>
    <mileage>17964</mileage>
    <year>2012</year>
    <user_defined name="title_status">salvage</user_defined>
</automobile>
<automobile>
    <mileage>198026</mileage>
    <year>1990</year>
</automobile>

The output I expect would look like this:

<automobile automobile_frequency="2">
    <mileage />
    <year />
    <user_defined name="color" />
</automobile>
<automobile automobile_frequency="1">
    <mileage />
    <year />
    <user_defined name="title_status" />
</automobile>
<automobile automobile_frequency="1">
    <mileage />
    <year />
</automobile>

I've implemented the code using iterparse, but when it's processing the elements, the attributes do not exist in the element. The code logic appears to be correct, but attributes simply don't exist; they are not written in the output, and they are not present for the uniqueness test. Per the above input example, this is what I get on output:

<root>
  <automobile automobile_frequency="3">
    <mileage/>
    <year/>
    <user_defined/>
  </automobile>
  <automobile automobile_frequency="1">
    <mileage/>
    <year/>
  </automobile>
</root>

The usage is:

xplore.py input.xml node_to_explore

In the above example, I used:

xplore.py trivial.xml automobile

Here's the source:

from lxml import etree
import sys
import re
from datetime import datetime

# global node signature map
structure_map = {}
# global code frequency map
frequency_map = {}
# output tree
tmp_root = etree.Element("tmp_root")

def process_element(el):
    global target
    if el.tag != target:
        return
    # get the structure of the element
    structure = get_structure(el)
    global structure_map
    structure_key = etree.tostring(structure, pretty_print=True)
    if structure_key not in structure_map.keys():
        # add signature to structure map
        structure_map[structure_key] = structure
        # add node to output
        global tmp_root
        tmp_root.append(structure)
        # add signature to frequency map
        frequency_map[structure_key] = 1
    else:
        # increment frequency map
        frequency_map[structure_key] += 1

# returns a unique string representing the structure of the node
# including attributes
def get_structure(el):
    # create new element for the return value
    ret = etree.Element(el.tag)
    # get attributes
    attribute_keys = el.attrib.keys()
    for attribute_key in attribute_keys:
        ret.set(attribute_key, el.get(attribute_key))
    # check for children
    children = list(el)
    for child in children:
        ret.append(get_structure(child))
    return ret

if len(sys.argv) < 3:
    print "Must specify an XML file for processing, as well as an element type!"
    exit(0)

# Get XML file
xml = sys.argv[1]
# Get output file name
output_file = xml[0:xml.rindex(".")]+".txt"
# get target element type to evaluate
target = sys.argv[2]
# mark start
startTime = datetime.now()
# Parse XML

print '==========================='
print 'Parsing XML'
print '==========================='
context = etree.iterparse(xml, events=('end',))
for event, element in context:
    process_element(element)
    element.clear()
# create tree sorted by frequency
ranked = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True)
root = etree.Element("root")
for item in ranked:
    structure = structure_map[item[0]]
    structure.set(target+"_frequency", str(item[1]))
    root.append(structure)
# pretty print root
out = open(output_file, 'w')
out.write(etree.tostring(root, pretty_print=True))
# output run time
time = datetime.now() - startTime
reg3 = re.compile("\\d+:\\d(\\d:\\d+\\.\\d{4})")
time = re.search(reg3, unicode(time))
time = "Runtime: %ss" % (time.group(1).encode("utf-8"))
print(time)

In the debugger, I can clearly see that the attributes are missing from elements in the calls to get_structure. Can anyone tell me why this is the case?

Body:
The data:

<root>
    <automobile>
        <mileage>20192</mileage>
        <year>2005</year>
        <user_defined name="color">red</user_defined>
    </automobile>
    <automobile>
        <mileage>1098</mileage>
        <year>2018</year>
        <user_defined name="color">blue</user_defined>
    </automobile>
    <automobile>
        <mileage>17964</mileage>
        <year>2012</year>
        <user_defined name="title_status">salvage</user_defined>
    </automobile>
    <automobile>
        <mileage>198026</mileage>
        <year>1990</year>
    </automobile>
</root>

The code:

from lxml import etree
import sys
import re
from datetime import datetime

# global node signature map
structure_map = {}
# global code frequency map
frequency_map = {}
# output tree
tmp_root = etree.Element("tmp_root")

def process_element(el):
    # get the structure of the element
    structure = get_structure(el)
    global structure_map
    structure_key = etree.tostring(structure, pretty_print=True)
    if structure_key not in structure_map.keys():
        # add signature to structure map
        structure_map[structure_key] = structure
        # add node to output
        global tmp_root
        tmp_root.append(structure)
        # add signature to frequency map
        frequency_map[structure_key] = 1
    else:
        # increment frequency map
        frequency_map[structure_key] += 1

# returns a unique string representing the structure of the node
# including attributes
def get_structure(el):
    # create new element for the return value
    ret = etree.Element(el.tag)
    # get attributes
    attribute_keys = el.attrib.keys()
    for attribute_key in attribute_keys:
        ret.set(attribute_key, el.get(attribute_key))
    # check for children
    children = list(el)
    for child in children:
        ret.append(get_structure(child))
    return ret

if len(sys.argv) < 3:
    print "Must specify an XML file for processing, as well as an element type!"
    exit(0)

# Get XML file
xml = sys.argv[1]
# Get output file name
output_file = xml[0:xml.rindex(".")]+".txt"
# get target element type to evaluate
target = sys.argv[2]
# mark start
startTime = datetime.now()
# Parse XML

print '==========================='
print 'Parsing XML'
print '==========================='
context = etree.iterparse(xml, events=('end',))
element_to_clear = []
for event, element in context:
    element_to_clear.append(element)
    global target
    if element.tag == target:
        process_element(element)
        for ele in element_to_clear:
            ele.clear()
        element_to_clear = []
# create tree sorted by frequency
ranked = sorted(frequency_map.items(), key=lambda x: x[1], reverse=True)
root = etree.Element("root")
for item in ranked:
    structure = structure_map[item[0]]
    structure.set(target+"_frequency", str(item[1]))
    root.append(structure)
# pretty print root
out = open(output_file, 'w')
out.write(etree.tostring(root, pretty_print=True))
# output run time
time = datetime.now() - startTime
reg3 = re.compile("\\d+:\\d(\\d:\\d+\\.\\d{4})")
time = re.search(reg3, unicode(time))
time = "Runtime: %ss" % (time.group(1).encode("utf-8"))
print(time)

The command: xplore.py trivial.xml automobile


问:
Javascript - Display a different content if a checkbox is active
I'm trying to set up something in JQuery but at the moment I'm not really sure I'm doing it right.

To keep it simple, I would like to display 4 checkboxes. These checkboxes serve as filters. For the example, let's say the first checkbox is spring, the second is summer, the third is autumn and the fourth is winter.

When I check the "summer" box I would like some text to be displayed. If I tick the autumn one, another text is displayed. Basically, I would like to display different texts depending on what is ticked.

```<code><script type="text/javascript">
    function ShowHideDiv(winter) {
        var winter_list = document.getElementById("winter_list");
        winter_list.style.display = winter.checked ? "block" : "none";
    }
</script>
<script type="text/javascript">
    function ShowHideDiv(summer) {
        var summer_list = document.getElementById("summer_list");
        summer_list.style.display = summer.checked ? "block" : "none";
    }
</script>

<label for="checkWinter">
    <input type="checkbox" id="winter" onclick="ShowHideDiv(winter)" />
    Winter
</label>
<label for="checkSummer">
    <input type="checkbox" id="summer" onclick="ShowHideDiv(summer)" />
    Summer
</label>
<hr />

<!-- For Winter -->
<div id="winter_list" style="display: none">
<p>Text come here</p>
</div>

<!-- For Summer -->
<div id="summer_list" style="display: none">
<p>Text come here for summer</p>
</div>
</code>```

If possible: Can we make it possible to tick more than one box?

I've been following tutorials on StackOverflow but so far without much success, as I haven't found anything in the genre of my same request.

Thanks

答:
The simplest, cleanest solution I could think of is this:

const ShowHideDiv = function (check, season) {
  let el = document.getElementById(season);

  // hide element(s)
  el.classList.add('hidden');

  // Show element(s) if checked
  if(check.checked === true){
    el.classList.remove('hidden');
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none;
}</code>```

    <input id="checkWinter" type="checkbox" onchange="ShowHideDiv(this, 'winter')" />
    Winter

    <input id="checkSummer" type="checkbox" onchange="ShowHideDiv(this, 'summer')" />
    Summer

    <input id="checkSpring" type="checkbox" onchange="ShowHideDiv(this, 'spring')" />
    Spring

Text come here  for winter

Text come here for summer

Text come here for spring

```

It works without changes for 2, 3 or 4 seasons.

Body:
I'm trying to set up something in JQuery but at the moment I'm not really sure I'm doing it right.

To keep it simple, I would like to display 4 checkboxes. These checkboxes serve as filters. For the example, let's say the first checkbox is spring, the second is summer, the third is autumn and the fourth is winter.

When I check the "summer" box I would like some text to be displayed. If I tick the autumn one, another text is displayed. Basically, I would like to display different texts depending on what is ticked.

    <input type="checkbox" id="winter" onclick="ShowHideDiv(winter)" />
    Winter

    <input type="checkbox" id="summer" onclick="ShowHideDiv(summer)" />
    Summer

Text come here

Text come here for summer

If possible: Can we make it possible to tick more than one box?

I've been following tutorials on StackOverflow but so far without much success, as I haven't found anything in the genre of my same request.

Thanks

Body:
The simplest, cleanest solution I could think of is this:

const ShowHideDiv = function (check, season) {
  let el = document.getElementById(season);

  // hide element(s)
  el.classList.add('hidden');

  // Show element(s) if checked
  if(check.checked === true){
    el.classList.remove('hidden');
  }
}

.hidden {
  display: none;
}

<label for="checkWinter">
    <input id="checkWinter" type="checkbox" onchange="ShowHideDiv(this, 'winter')" />
    Winter
</label>
<label for="checkSummer">
    <input id="checkSummer" type="checkbox" onchange="ShowHideDiv(this, 'summer')" />
    Summer
</label>
<label for="checkSpring">
    <input id="checkSpring" type="checkbox" onchange="ShowHideDiv(this, 'spring')" />
    Spring
</label>
<hr />

<!-- For Winter -->
<div class="hidden" id="winter">
  <p>Text come here  for winter</p>
</div>

<!-- For Summer -->
<div class="hidden" id="summer">
  <p>Text come here for summer</p>
</div>

<!-- For Spring -->
<div class="hidden" id="spring">
  <p>Text come here for spring</p>
</div>

It works without changes for 2, 3 or 4 seasons.


问:
inspec-aws errors on running an exec
Any idea what im doing wrong i have chefworkstation installed:

```<code>$ chef -v
Chef Workstation version: 21.4.365
Chef Infra Client version: 16.12.3
Chef InSpec version: 4.29.3
Chef CLI version: 4.0.0
Chef Habitat version: 1.6.288
Test Kitchen version: 2.11.2
Cookstyle version: 7.10.0
</code>```

aws cli is installed and i have set up a default credentials that are working (confirmed via deploying some tf code)

Created a folder and ran

```<code>inspec init profile --platform aws tftest
</code>```

Install the aws-sdk  for 2.7.3   (Using rbenv) and bundle to install the sdk

Gemfile

```<code>source 'https://rubygems.org/' do
    gem 'aws-sdk', '~> 3'
end
</code>```

I then run:

```<code>inspec exec tftest -t aws://
</code>```

and get the below error:

```<code>$ inspec exec tftest -t aws://
Traceback (most recent call last):
        30: from /usr/bin/inspec:354:in `<main>'
        29: from /usr/bin/inspec:354:in `load'
        28: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-bin-4.29.3/bin/inspec:11:in `<top (required)>'
        27: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/base_cli.rb:35:in `start'
        26: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor/base.rb:485:in `start'
        25: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
        24: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
        23: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
        22: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/cli.rb:281:in `exec'
        21: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:135:in `run'
        20: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:101:in `load'
        19: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:101:in `each'
        18: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:107:in `block in load'
        17: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:259:in `load_libraries'
        16: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:259:in `each_with_index'
        15: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:259:in `each'
        14: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:278:in `block in load_libraries'
        13: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:285:in `load_libraries'
        12: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:143:in `load_libraries'
        11: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:143:in `each'
        10: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:144:in `block in load_libraries'
         9: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:159:in `load_library_file'
         8: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:170:in `load_with_context'
         7: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:170:in `instance_eval'
         6: from libraries/aws_alb.rb:3:in `load_with_context'
         5: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/dsl_shared.rb:47:in `require'
         4: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/dsl_shared.rb:47:in `eval'
         3: from libraries/aws_backend.rb:13:in `create'
         2: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/dsl_shared.rb:33:in `require'
         1: from /opt/chef-workstation/embedded/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:83:in `require'
/opt/chef-workstation/embedded/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:83:in `require': cannot load such file -- aws-sdk-ecrpublic (LoadError)
</code>```

I tried updating my Gemfile  to include  gem 'aws-sdk-ecrpublic'  but i still get the same error

folder layout is:

```<code>.
├── Gemfile
├── Gemfile.lock
├── README.md
├── .ruby-version
└── tftest
    ├── controls
    │   └── example.rb
    ├── inspec.lock
    ├── inspec.yml
    └── README.md
</code>```

Any idea whats wrong?

答: its a very late answer to this question but inspec-aws has dependency on train-aws which need to be installed. https://github.com/inspec/train-aws</p>

Title: inspec-aws errors on running an exec

Body:
Any idea what im doing wrong i have chefworkstation installed:

$ chef -v
Chef Workstation version: 21.4.365
Chef Infra Client version: 16.12.3
Chef InSpec version: 4.29.3
Chef CLI version: 4.0.0
Chef Habitat version: 1.6.288
Test Kitchen version: 2.11.2
Cookstyle version: 7.10.0

aws cli is installed and i have set up a default credentials that are working (confirmed via deploying some tf code)

Created a folder and ran

inspec init profile --platform aws tftest

Install the aws-sdk  for 2.7.3   (Using rbenv) and bundle to install the sdk

Gemfile

source 'https://rubygems.org/' do
    gem 'aws-sdk', '~> 3'
end

I then run:

inspec exec tftest -t aws://

and get the below error:

$ inspec exec tftest -t aws://
Traceback (most recent call last):
        30: from /usr/bin/inspec:354:in `'
        29: from /usr/bin/inspec:354:in `load'
        28: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-bin-4.29.3/bin/inspec:11:in `<top (required)>'
        27: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/base_cli.rb:35:in `start'
        26: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor/base.rb:485:in `start'
        25: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
        24: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
        23: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
        22: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/cli.rb:281:in `exec'
        21: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:135:in `run'
        20: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:101:in `load'
        19: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:101:in `each'
        18: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/runner.rb:107:in `block in load'
        17: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:259:in `load_libraries'
        16: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:259:in `each_with_index'
        15: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:259:in `each'
        14: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:278:in `block in load_libraries'
        13: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile.rb:285:in `load_libraries'
        12: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:143:in `load_libraries'
        11: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:143:in `each'
        10: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:144:in `block in load_libraries'
         9: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:159:in `load_library_file'
         8: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:170:in `load_with_context'
         7: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/profile_context.rb:170:in `instance_eval'
         6: from libraries/aws_alb.rb:3:in `load_with_context'
         5: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/dsl_shared.rb:47:in `require'
         4: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/dsl_shared.rb:47:in `eval'
         3: from libraries/aws_backend.rb:13:in `create'
         2: from /opt/chef-workstation/embedded/lib/ruby/gems/2.7.0/gems/inspec-core-4.29.3/lib/inspec/dsl_shared.rb:33:in `require'
         1: from /opt/chef-workstation/embedded/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:83:in `require'
/opt/chef-workstation/embedded/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:83:in `require': cannot load such file -- aws-sdk-ecrpublic (LoadError)

I tried updating my Gemfile  to include  gem 'aws-sdk-ecrpublic'  but i still get the same error

folder layout is:

.
├── Gemfile
├── Gemfile.lock
├── README.md
├── .ruby-version
└── tftest
    ├── controls
    │   └── example.rb
    ├── inspec.lock
    ├── inspec.yml
    └── README.md

Any idea whats wrong?


问:
Finding average value in pandas
I have this pandas Dataframe:

```<code>name        price
Hyundai     $25000
Hyundai     $35000
Peugeot     $43250
BMW         $80000
Hyundai     $23000
Peugeot     $46000
BMW         $90000
Peugeot     $30500
</code>```

and I want to find the name that has biggest price average using pandas library.

Any help would be appreciated.

答:
Remove $ with converting values to numeric, here integers, aggregate mean and last get name by maximal value by Series.idxmax:

```<code>out = df['price'].str.strip('$').astype(int).groupby(df['name']).mean().idxmax()
print (out)
BMW
</code>```

Details:

```<code>print (df['price'].str.strip('$').astype(int))
0    25000
1    35000
2    43250
3    80000
4    23000
5    46000
6    90000
7    30500
Name: price, dtype: int32

print (df['price'].str.strip('$').astype(int).groupby(df['name']).mean())
name
BMW        85000.000000
Hyundai    27666.666667
Peugeot    39916.666667
Name: price, dtype: float64
</code>```

Title: Finding average value in pandas

Body:
I have this pandas Dataframe:

name        price
Hyundai     $25000
Hyundai     $35000
Peugeot     $43250
BMW         $80000
Hyundai     $23000
Peugeot     $46000
BMW         $90000
Peugeot     $30500

and I want to find the name that has biggest price average using pandas library.

Any help would be appreciated.

Body:
Remove $ with converting values to numeric, here integers, aggregate mean and last get name by maximal value by Series.idxmax:

out = df['price'].str.strip('$').astype(int).groupby(df['name']).mean().idxmax()
print (out)
BMW

Details:

print (df['price'].str.strip('$').astype(int))
0    25000
1    35000
2    43250
3    80000
4    23000
5    46000
6    90000
7    30500
Name: price, dtype: int32

print (df['price'].str.strip('$').astype(int).groupby(df['name']).mean())
name
BMW        85000.000000
Hyundai    27666.666667
Peugeot    39916.666667
Name: price, dtype: float64


问:
Missing data fields in Wikidata Query Service results despite items having these data
I am trying to retrieve some municipalities from Wikidata using SPARQL but several items returned have much of their fields empty despite these items having these data. I do not understand what is wrong with the query below (link to WQS). For example, the municipality Almelo has its coordinates (P625), and parent place (P131) erroneously missing in the results:

```<code>SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
  ?mun p:P31 ?instanceOf # Get statement because we need this later
       .
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.

  OPTIONAL {
    ?mun wdt:P625 ?coords;
      wdt:P131 ?parentPlace;
      wdt:P2046 ?area
      .
  }

  MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time

  service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel
</code>```

答:
This is because you are using one OPTIONAL statement instead of 3 separately.
In this case, Almelo doesn't have an 'area', wdt:P2046, so the whole OPTIONAL statement evaluates as false, and so it binds no variables.

The following query works:
Notice that we have 3 distinct optional statements, so that they may fail to bind variables independently of each other.

```<code>SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
  ?mun p:P31 ?instanceOf # Get statement because we need this later
       .
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.

  OPTIONAL {?mun wdt:P625 ?coords }
  OPTIONAL {?mun wdt:P131 ?parentPlace }
  OPTIONAL {?mun wdt:P2046 ?area }

  MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time

  service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel
</code>```

Body:
I am trying to retrieve some municipalities from Wikidata using SPARQL but several items returned have much of their fields empty despite these items having these data. I do not understand what is wrong with the query below (<a href="https://query.wikidata.org/#%20%20%20%20SELECT%20%3Fmun%20%3FmunLabel%20%3Fcoords%20%3FparentPlace%20%3Farea%20WHERE%20%7B%0A%20%20%20%20%20%20%3Fmun%20p%3AP31%20%3FinstanceOf%20%23%20Get%20statement%20because%20we%20need%20this%20later%0A%20%20%20%20%20%20%20%20%20%20%20.%0A%20%20%20%20%20%20%3FinstanceOf%20ps%3AP31%2Fwdt%3A279%2A%20wd%3AQ2039348.%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20OPTIONAL%20%7B%0A%20%20%20%20%20%20%20%20%3Fmun%20wdt%3AP625%20%3Fcoords%3B%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP131%20%3FparentPlace%3B%20%0A%20%20%20%20%20%20%20%20%20%20wdt%3AP2046%20%3Farea%0A%20%20%20%20%20%20%20%20%20%20.%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20MINUS%20%7B%20%3FinstanceOf%20pq%3AP582%20%3FendTime.%20%7D%20%23%20Don%27t%20show%20municipalities%20that%20have%20an%20end%20time%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20service%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%0A%20%20%20%20%7D%20ORDER%20BY%20%3FmunLabel" rel="nofollow noreferrer">link to WQS). For example, the municipality Almelo has its coordinates (P625), and parent place (P131) erroneously missing in the results:

SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
  ?mun p:P31 ?instanceOf # Get statement because we need this later
       .
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.

  OPTIONAL {
    ?mun wdt:P625 ?coords;
      wdt:P131 ?parentPlace;
      wdt:P2046 ?area
      .
  }

  MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time

  service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel

Body:
This is because you are using one OPTIONAL statement instead of 3 separately.
In this case, Almelo doesn't have an 'area', wdt:P2046, so the whole OPTIONAL statement evaluates as false, and so it binds no variables.

The following query works:
Notice that we have 3 distinct optional statements, so that they may fail to bind variables independently of each other.

SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
  ?mun p:P31 ?instanceOf # Get statement because we need this later
       .
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.

  OPTIONAL {?mun wdt:P625 ?coords }
  OPTIONAL {?mun wdt:P131 ?parentPlace }
  OPTIONAL {?mun wdt:P2046 ?area }

  MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time

  service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel


问:
Can't access form data in PHP
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

```<code><?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>
</code>```

Form Process:

```<code><?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>
</code>```

Result:

```<code>Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }
</code>```

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

答:
That's because you're not using the right  brackets. It has to be:</p>

```<code>$_POST['name'];
</code>```

Title: Can't access form data in PHP

Body:
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>

                        name:
                        <input type='Text' name='name' value='anon' />

                        <input type='submit' name='send' value='Send' />

        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "
";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

Body:
That's because you're not using the right  brackets. It has to be:

$_POST['name'];


问:
Django how to set a class based view queryset with function return
im trying to make endless pagination with filtered data and im geting the data with get request.

views.py:

```<code>class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        renkler = Renk.objects.all()
        beden = Varyasyon.objects.all()
        katagori = Grub.objects.all()
        order = self.request.GET.get('order')
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if self.request.GET.getlist("varyasyon_id__in"):
            filtered = filtered.filter(
                Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
            )
        if self.request.GET.getlist("renk_id__in"):
            filtered = filtered.filter(
                Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
            )
        if self.request.GET.getlist("grub_id__in"):
            filtered = filtered.filter(
                Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
            )

        if order == "date":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )
        elif order == "sale":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
        )
        elif order == "tesettur":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
        )
        else:
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )

        context = {"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'filtered':filters,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat}
        self.queryset = context
        return context
    queryset = get_context_data()
</code>```

i want to set the queryset from get_context_data's return but it asks for self argument.

error

```<code>TypeError: ProductsView.get_context_data() missing 1 required positional argument: 'self'
</code>```

when i define queryset on the top it says that get_context_data is not defined.

答:
try to override get_queryset() like this and then override your context using get_context_data i tried it and it worked for me.

```<code>class ProductsView(ListView):
paginate_by = 12
context_object_name = 'filtered'
template_name = 'urunler.html'

def get_queryset(self):
    order = self.request.GET.get('order')
    filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
    checked_var = self.request.GET.getlist('varyasyon_id__in')
    checked_renk = self.request.GET.getlist('renk_id__in')
    checked_kat = self.request.GET.getlist('grub_id__in')
    if self.request.GET.getlist("varyasyon_id__in"):
        filtered = filtered.filter(
            Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
        )
    if self.request.GET.getlist("renk_id__in"):
        filtered = filtered.filter(
            Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
        )
    if self.request.GET.getlist("grub_id__in"):
        filtered = filtered.filter(
            Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
        )

    if order == "date":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    elif order == "sale":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
    )
    elif order == "tesettur":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
    )
    else:
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    return filters

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)

    renkler = Renk.objects.all()
    beden = Varyasyon.objects.all()
    katagori = Grub.objects.all()
    order = self.request.GET.get('order')

    filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
    checked_var = self.request.GET.getlist('varyasyon_id__in')
    checked_renk = self.request.GET.getlist('renk_id__in')
    checked_kat = self.request.GET.getlist('grub_id__in')
    if self.request.GET.getlist("varyasyon_id__in"):
        filtered = filtered.filter(
            Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
        )
    if self.request.GET.getlist("renk_id__in"):
        filtered = filtered.filter(
            Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
        )
    if self.request.GET.getlist("grub_id__in"):
        filtered = filtered.filter(
            Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
        )

    if order == "date":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    elif order == "sale":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
    )
    elif order == "tesettur":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
    )
    else:
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    context.update({"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat})
    return context
</code>```

Body:
im trying to make endless pagination with filtered data and im geting the data with get request.

views.py:

class ProductsView(ListView):

    paginate_by = 20
    context_object_name = 'products'
    template_name = "urunler.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        renkler = Renk.objects.all()
        beden = Varyasyon.objects.all()
        katagori = Grub.objects.all()
        order = self.request.GET.get('order')
        filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
        checked_var = self.request.GET.getlist('varyasyon_id__in')
        checked_renk = self.request.GET.getlist('renk_id__in')
        checked_kat = self.request.GET.getlist('grub_id__in')
        if self.request.GET.getlist("varyasyon_id__in"):
            filtered = filtered.filter(
                Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
            )
        if self.request.GET.getlist("renk_id__in"):
            filtered = filtered.filter(
                Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
            )
        if self.request.GET.getlist("grub_id__in"):
            filtered = filtered.filter(
                Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
            )

        if order == "date":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )
        elif order == "sale":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
        )
        elif order == "tesettur":
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
        )
        else:
            filters = filtered.filter(
            Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
        )

        context = {"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'filtered':filters,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat}
        self.queryset = context
        return context
    queryset = get_context_data()

i want to set the queryset from get_context_data's return but it asks for self argument.

error

TypeError: ProductsView.get_context_data() missing 1 required positional argument: 'self'

when i define queryset on the top it says that get_context_data is not defined.

Body:
try to override get_queryset() like this and then override your context using get_context_data i tried it and it worked for me.

class ProductsView(ListView):
paginate_by = 12
context_object_name = 'filtered'
template_name = 'urunler.html'

def get_queryset(self):
    order = self.request.GET.get('order')
    filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
    checked_var = self.request.GET.getlist('varyasyon_id__in')
    checked_renk = self.request.GET.getlist('renk_id__in')
    checked_kat = self.request.GET.getlist('grub_id__in')
    if self.request.GET.getlist("varyasyon_id__in"):
        filtered = filtered.filter(
            Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
        )
    if self.request.GET.getlist("renk_id__in"):
        filtered = filtered.filter(
            Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
        )
    if self.request.GET.getlist("grub_id__in"):
        filtered = filtered.filter(
            Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
        )

    if order == "date":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    elif order == "sale":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
    )
    elif order == "tesettur":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
    )
    else:
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    return filters

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)

    renkler = Renk.objects.all()
    beden = Varyasyon.objects.all()
    katagori = Grub.objects.all()
    order = self.request.GET.get('order')

    filtered = Stok.objects.all().order_by('-urun_id__kayit_tarihi','foto').distinct('urun_id__kayit_tarihi','foto')
    checked_var = self.request.GET.getlist('varyasyon_id__in')
    checked_renk = self.request.GET.getlist('renk_id__in')
    checked_kat = self.request.GET.getlist('grub_id__in')
    if self.request.GET.getlist("varyasyon_id__in"):
        filtered = filtered.filter(
            Q(varyasyon_id__in = self.request.GET.getlist("varyasyon_id__in"))
        )
    if self.request.GET.getlist("renk_id__in"):
        filtered = filtered.filter(
            Q(renk_id__in = self.request.GET.getlist("renk_id__in"))
        )
    if self.request.GET.getlist("grub_id__in"):
        filtered = filtered.filter(
            Q(grub_id__in = self.request.GET.getlist("grub_id__in"))
        )

    if order == "date":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    elif order == "sale":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(indirim = True)
    )
    elif order == "tesettur":
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0) & Q(urun_id__tesettur = True)
    )
    else:
        filters = filtered.filter(
        Q(urun_id__yayin = True) & Q(stok_adet__gt = 0)
    )
    context.update({"renkler":renkler,"bedenler":beden,"katagoriler":katagori,'checkedvar':checked_var,'checkedrenk':checked_renk,'checkedkat':checked_kat})
    return context