text:
Q: API Platform slow on collections I'm creating a web API with API Platform framework and I'm getting some performance issues with collections retrieving.
Problem
I would like to get a collection of a table (with relations) but it takes 20 secondes to load.
Additional informations

*

*Pagination enabled (by default 30 items / page).

*I use Symfony server:start for working.

*I work in WSL2 (in /home folder)

*I use MariaDB in docker

*APCu Enabled

*API Platform is not inside docker

Firstly I was expecting an I/O issue because I was working in /mnt. I moved the project into /home and in fact performances were better except for when I tried to get the collection.
Then, I tried to get other collections and some of them worked fast.
I also tried to queryparam with itemPage = 1 but it takes between 15 and 20 secondes...
I'm supposing the problem can be encountered against the code but I'm not sure...
Here are some logs :
The entity
<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Controller\ContactsFromTagController;
use Symfony\Component\Serializer\Annotation\Groups;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\NumericFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
/**
 * Contacts
 *
 * @ORM\Table(name="contacts", indexes={@ORM\Index(name="contactIdPersonne", columns={"idPersonne"}), @ORM\Index(name="contactIdAdresse", columns={"idAdresse"}), @ORM\Index(name="contactIdOrganisation", columns={"idOrganisation"})})
 * @ORM\Entity(repositoryClass="App\Repository\ContactsRepository")
 *
 * @ApiResource(
 *      normalizationContext={
 *          "groups"={"contacts:read"}
 *      },
 *      collectionOperations={
 *          "get",
 *          "post",
 *          "get_manager_datas"={
 *              "method" = "GET",
 *              "path" = "/list_manager_datas",
 *              "controller" = ContactsFromTagController::class
 *           }
 *      }
 * )
 *
 * @ApiFilter(NumericFilter::class, properties={"actif"})
 * @ApiFilter(SearchFilter::class, properties={"idContact": "exact"})
 * @ApiFilter(SearchFilter::class, properties={"personne.nom": "start"})
 * @ApiFilter(SearchFilter::class, properties={"personne.prenom": "start"})
 */
class Contacts
{
    /**
     * @var int
     *
     * @ORM\Column(name="idContact", type="smallint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @Groups({"contacts:read", "actionclients:in"})
     */
    private $idContact;

    /**
     * @var string|null
     *
     * @ORM\Column(name="libelle", type="string", length=100, nullable=true)
     * @Groups({"contacts:read"})
     */
    private $libelle;

    /**
     * @var string|null
     *
     * @ORM\Column(name="fonction", type="string", length=100, nullable=true)
     * @Groups("contacts:read")
     */
    private $fonction;

    /**
     * @var string|null
     *
     * @ORM\Column(name="departement", type="string", length=100, nullable=true)
     * @Groups("contacts:read")
     */
    private $departement;

    /**
     * @var string|null
     *
     * @ORM\Column(name="login", type="string", length=6, nullable=true)
     * @Groups("contacts:read")
     */
    private $login;

    /**
     * @var string|null
     *
     * @ORM\Column(name="numeroPointage", type="string", length=6, nullable=true)
     * @Groups("contacts:read")
     */
    private $numeroPointage;

    /**
     * @var int|null
     *
     * @ORM\Column(name="actif", type="smallint", nullable=true)
     * @Groups("contacts:read")
     */
    private $actif;

    /**
     * @var int|null
     *
     * @ORM\Column(name="demandeSuppression", type="smallint", nullable=true)
     * @Groups("contacts:read")
     */
    private $demandeSuppression;

    /**
     * @var string|null
     *
     * @ORM\Column(name="statut", type="string", length=10, nullable=true)
     * @Groups("contacts:read")
     */
    private $statut;

    /**
     * @var \Adresses
     *
     * @ORM\ManyToOne(targetEntity="Adresses")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idAdresse", referencedColumnName="idAdresse")
     * })
     * @Groups("contacts:read")
     */
    private $adresse;

    /**
     * @var \Organisations
     *
     * @ORM\ManyToOne(targetEntity="Organisations")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idOrganisation", referencedColumnName="idOrganisation")
     * })
     * @ApiFilter(NumericFilter::class, properties={"organisation.idOrganisation"})
     * @Groups({"contacts:read", "actionclients:in"})
     */
    private $organisation;

    /**
     * @var \Personnes
     *
     * @ORM\ManyToOne(targetEntity="Personnes")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idPersonne", referencedColumnName="idPersonne")
     * })
     * @Groups({"contacts:read", "actionclients:in"})
     */
    private $personne;

    /**
     * @ORM\OneToMany(targetEntity=Tagsattribues::class, mappedBy="contact")
     * @Groups("contacts:read")
     */
    private $tagsAttribues;

    /**
     * @ORM\OneToMany(targetEntity=Coordonnees::class, mappedBy="contact")
     * @Groups("contacts:read")
     */
    private $coordonnees;

    public function __construct()
    {
        $this->tagsAttribues = new ArrayCollection();
        $this->coordonnees = new ArrayCollection();
    }

    public function getIdContact(): ?int
    {
        return $this->idContact;
    }

    public function getLibelle(): ?string
    {
        return $this->libelle;
    }

    public function setLibelle(?string $libelle): self
    {
        $this->libelle = $libelle;

        return $this;
    }

    public function getFonction(): ?string
    {
        return $this->fonction;
    }

    public function setFonction(?string $fonction): self
    {
        $this->fonction = $fonction;

        return $this;
    }

    public function getDepartement(): ?string
    {
        return $this->departement;
    }

    public function setDepartement(?string $departement): self
    {
        $this->departement = $departement;

        return $this;
    }

    public function getLogin(): ?string
    {
        return $this->login;
    }

    public function setLogin(?string $login): self
    {
        $this->login = $login;

        return $this;
    }

    public function getNumeroPointage(): ?string
    {
        return $this->numeroPointage;
    }

    public function setNumeroPointage(?string $numeroPointage): self
    {
        $this->numeroPointage = $numeroPointage;

        return $this;
    }

    public function getActif(): ?int
    {
        return $this->actif;
    }

    public function setActif(?int $actif): self
    {
        $this->actif = $actif;

        return $this;
    }

    public function getDemandeSuppression(): ?int
    {
        return $this->demandeSuppression;
    }

    public function setDemandeSuppression(?int $demandeSuppression): self
    {
        $this->demandeSuppression = $demandeSuppression;

        return $this;
    }

    public function getStatut(): ?string
    {
        return $this->statut;
    }

    public function setStatut(?string $statut): self
    {
        $this->statut = $statut;

        return $this;
    }

    public function getAdresse(): ?Adresses
    {
        return $this->adresse;
    }

    public function setAdresse(?Adresses $adresse): self
    {
        $this->adresse = $adresse;

        return $this;
    }

    public function getOrganisation(): ?Organisations
    {
        return $this->organisation;
    }

    public function setOrganisation(?Organisations $organisation): self
    {
        $this->organisation = $organisation;

        return $this;
    }

    public function getPersonne(): ?Personnes
    {
        return $this->personne;
    }

    public function setPersonne(?Personnes $personne): self
    {
        $this->personne = $personne;

        return $this;
    }

    /**
     * @return Collection|Tagsattribues[]
     */
    public function getTagsAttribues(): Collection
    {
        return $this->tagsAttribues;
    }

    public function addTagsAttribue(Tagsattribues $tagsAttribue): self
    {
        if (!$this->tagsAttribues->contains($tagsAttribue)) {
            $this->tagsAttribues[] = $tagsAttribue;
            $tagsAttribue->setContacts($this);
        }

        return $this;
    }

    public function removeTagsAttribue(Tagsattribues $tagsAttribue): self
    {
        if ($this->tagsAttribues->removeElement($tagsAttribue)) {
            // set the owning side to null (unless already changed)
            if ($tagsAttribue->getContacts() === $this) {
                $tagsAttribue->setContacts(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Coordonnees[]
     */
    public function getCoordonnees(): Collection
    {
        return $this->coordonnees;
    }

    public function addCoordonnee(Coordonnees $coordonnee): self
    {
        if (!$this->coordonnees->contains($coordonnee)) {
            $this->coordonnees[] = $coordonnee;
            $coordonnee->setContact($this);
        }

        return $this;
    }

    public function removeCoordonnee(Coordonnees $coordonnee): self
    {
        if ($this->coordonnees->removeElement($coordonnee)) {
            // set the owning side to null (unless already changed)
            if ($coordonnee->getContact() === $this) {
                $coordonnee->setContact(null);
            }
        }

        return $this;
    }

}

[
  {
    "idContact": 0,
    "libelle": "string",
    "fonction": "string",
    "departement": "string",
    "login": "string",
    "numeroPointage": "string",
    "actif": 0,
    "demandeSuppression": 0,
    "statut": "string",
    "adresse": {
      "idAdresse": 0,
      "libelle": "string",
      "batimentfr": "string",
      "batimentnl": "string",
      "ruefr": "string",
      "ruenl": "string"
    },
    "organisation": {
      "idOrganisation": 0,
      "denominationfr": "string",
      "denominationnl": "string",
      "abreviationfr": "string",
      "abreviationnl": "string",
      "organisme": "string",
      "libelleorganisme": "string",
      "dossierkp": "string",
      "iduserkb": 0,
      "isclient": true,
      "idclientnavision": "string",
      "isfournisseur": true,
      "idfournisseurnavision": "string",
      "numeroentreprise": "string",
      "bilingue": 0,
      "fictif": 0,
      "actif": 0
    },
    "personne": {
      "idPersonne": 0,
      "genre": "string",
      "particule": "string",
      "nom": "string",
      "prenom": "string",
      "roleLinguistique": "string",
      "homonyme": "string",
      "actif": true,
      "statut": "string"
    },
    "tagsAttribues": [
      {
        "idTagAttribue": 0,
        "tag": {
          "idTag": 0,
          "libellefr": "string",
          "libellenl": "string",
          "actif": true,
          "hereditaire": true,
          "public": true,
          "tagsDivisions": [
            "string"
          ]
        }
      }
    ],
    "coordonnees": [
      {
        "idCoordonnee": 0,
        "contenu": "string",
        "pays": {
          "idPays": 0,
          "code": "string",
          "libellefr": "string",
          "libellenl": "string",
          "libelleen": "string",
          "prefixe": "string"
        },
        "typeCoordonnee": {
          "idTypeCoordonnee": 0,
          "nature": "string",
          "libellefr": "string",
          "libellenl": "string",
          "glyphicon": "string"
        }
      }
    ]
  }
]

From debugger of Symfony server
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [info] Matched route "api_contacts_get_collection".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Checking for authenticator support.
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Nelmio\CorsBundle\EventListener\CorsListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::setDefaultLocale".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\EventListener\QueryParameterValidateListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::configureLogoutUrlGenerator".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\EventListener\AddFormatListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\EventListener\ReadListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\Security\EventListener\DenyAccessListener::onSecurity".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\EventListener\DeserializeListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\Security\EventListener\DenyAccessListener::onSecurityPostDenormalize".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.request" to listener "ApiPlatform\Core\Bridge\Symfony\Bundle\EventListener\SwaggerUiListener::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] Notified event "kernel.controller_arguments" to listener "Symfony\Component\HttpKernel\EventListener\ErrorListener::onControllerArguments".
[PHP-FPM    ] [25-Nov-2022 15:37:05 Europe/Berlin] [debug] SELECT DISTINCT c0_.idContact AS idContact_0, c0_.idContact AS idContact_1 FROM contacts c0_ LEFT JOIN adresses a1_ ON c0_.idAdresse = a1_.idAdresse LEFT JOIN organisations o2_ ON c0_.idOrganisation = o2_.idOrganisation LEFT JOIN personnes p3_ ON c0_.idPersonne = p3_.idPersonne LEFT JOIN tagsattribues t4_ ON c0_.idContact = t4_.idContact LEFT JOIN tags t5_ ON t4_.idTag = t5_.idTag LEFT JOIN coordonnees c6_ ON c0_.idContact = c6_.idContact LEFT JOIN pays p7_ ON c6_.idPays = p7_.idPays LEFT JOIN typescoordonnees t8_ ON c6_.idTypeCoordonnee = t8_.idTypeCoordonnee ORDER BY c0_.idContact ASC LIMIT 1
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] SELECT c0_.idContact AS idContact_0, c0_.libelle AS libelle_1, c0_.fonction AS fonction_2, c0_.departement AS departement_3, c0_.login AS login_4, c0_.numeroPointage AS numeroPointage_5, c0_.actif AS actif_6, c0_.demandeSuppression AS demandeSuppression_7, c0_.statut AS statut_8, a1_.idAdresse AS idAdresse_9, a1_.libelle AS libelle_10, a1_.batimentFr AS batimentFr_11, a1_.batimentNl AS batimentNl_12, a1_.rueFr AS rueFr_13, a1_.rueNl AS rueNl_14, a1_.numero AS numero_15, a1_.boite AS boite_16, a1_.statut AS statut_17, o2_.idOrganisation AS idOrganisation_18, o2_.denominationFr AS denominationFr_19, o2_.denominationNl AS denominationNl_20, o2_.abreviationFr AS abreviationFr_21, o2_.abreviationNl AS abreviationNl_22, o2_.organisme AS organisme_23, o2_.libelleOrganisme AS libelleOrganisme_24, o2_.dossierKP AS dossierKP_25, o2_.idUserKb AS idUserKb_26, o2_.isClient AS isClient_27, o2_.idClientNavision AS idClientNavision_28, o2_.isFournisseur AS isFournisseur_29, o2_.idFournisseurNavision AS idFournisseurNavision_30, o2_.numeroEntreprise AS numeroEntreprise_31, o2_.bilingue AS bilingue_32, o2_.fictif AS fictif_33, o2_.actif AS actif_34, p3_.idPersonne AS idPersonne_35, p3_.genre AS genre_36, p3_.particule AS particule_37, p3_.nom AS nom_38, p3_.prenom AS prenom_39, p3_.roleLinguistique AS roleLinguistique_40, p3_.homonyme AS homonyme_41, p3_.actif AS actif_42, p3_.statut AS statut_43, t4_.idTagAttribue AS idTagAttribue_44, t5_.idTag AS idTag_45, t5_.libelleFr AS libelleFr_46, t5_.libelleNl AS libelleNl_47, t5_.actif AS actif_48, t5_.hereditaire AS hereditaire_49, t5_.public AS public_50, c6_.idCoordonnee AS idCoordonnee_51, c6_.contenu AS contenu_52, p7_.idPays AS idPays_53, p7_.code AS code_54, p7_.libelleFr AS libelleFr_55, p7_.libelleNl AS libelleNl_56, p7_.libelleEn AS libelleEn_57, p7_.prefixe AS prefixe_58, t8_.idTypeCoordonnee AS idTypeCoordonnee_59, t8_.souche AS souche_60, t8_.nature AS nature_61, t8_.libelleFr AS libelleFr_62, t8_.libelleNl AS libelleNl_63, t8_.glyphicon AS glyphicon_64, c0_.idAdresse AS idAdresse_65, c0_.idOrganisation AS idOrganisation_66, c0_.idPersonne AS idPersonne_67, a1_.idLocalite AS idLocalite_68, a1_.idOrganisation AS idOrganisation_69, t4_.idOrganisation AS idOrganisation_70, t4_.idTag AS idTag_71, t4_.idContact AS idContact_72, c6_.idContact AS idContact_73, c6_.idOrganisation AS idOrganisation_74, c6_.idPays AS idPays_75, c6_.idTypeCoordonnee AS idTypeCoordonnee_76 FROM contacts c0_ LEFT JOIN adresses a1_ ON c0_.idAdresse = a1_.idAdresse LEFT JOIN organisations o2_ ON c0_.idOrganisation = o2_.idOrganisation LEFT JOIN personnes p3_ ON c0_.idPersonne = p3_.idPersonne LEFT JOIN tagsattribues t4_ ON c0_.idContact = t4_.idContact LEFT JOIN tags t5_ ON t4_.idTag = t5_.idTag LEFT JOIN coordonnees c6_ ON c0_.idContact = c6_.idContact LEFT JOIN pays p7_ ON c6_.idPays = p7_.idPays LEFT JOIN typescoordonnees t8_ ON c6_.idTypeCoordonnee = t8_.idTypeCoordonnee WHERE c0_.idContact IN (?) ORDER BY c0_.idContact ASC
[Web Server ] Nov 25 15:37:16 |INFO   | SERVER GET  (200) /api/contacts?page=1&itemsPerPage=1 ip="::1"
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] SELECT t0.idTagDivision AS idTagDivision_1, t0.idOrganisation AS idOrganisation_2, t0.idTag AS idTag_3 FROM tagsdivisions t0 WHERE t0.idTag = ?
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] SELECT t0.idTagDivision AS idTagDivision_1, t0.idOrganisation AS idOrganisation_2, t0.idTag AS idTag_3 FROM tagsdivisions t0 WHERE t0.idTag = ?
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.view" to listener "ApiPlatform\Core\Validator\EventListener\ValidateListener::onKernelView".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.view" to listener "App\EventSubscriber\LogSubscriber::onKernelRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.view" to listener "ApiPlatform\Core\EventListener\WriteListener::onKernelView".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.view" to listener "ApiPlatform\Core\EventListener\SerializeListener::onKernelView".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.view" to listener "ApiPlatform\Core\EventListener\RespondListener::onKernelView".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Listener "ApiPlatform\Core\EventListener\RespondListener::onKernelView" stopped propagation of the event "kernel.view".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Nelmio\CorsBundle\EventListener\CorsListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Nelmio\CorsBundle\EventListener\CacheableResponseVaryListener::onResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "ApiPlatform\Core\Hydra\EventListener\AddLinkHeaderListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\WebLink\EventListener\AddLinkHeaderListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "ApiPlatform\Core\HttpCache\EventListener\AddHeadersListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "ApiPlatform\Core\HttpCache\EventListener\AddTagsListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\ErrorListener::removeCspHeader".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\DisallowRobotsIndexingListener::onResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.response" to listener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelFinishRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\SessionListener::onFinishRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelFinishRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.finish_request" to listener "Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener::onKernelFinishRequest".
[PHP-FPM    ] [25-Nov-2022 15:37:16 Europe/Berlin] [debug] Notified event "kernel.finish_request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleAwareListener::onKernelFinishRequest".

Request : http://localhost:8000/api/contacts?page=1&itemsPerPage=30
Do you have any idea about the performances issues?


text:
Q: Set Components in Alternating Columns GridBagLayout Is there a way to set components in alternating columns 0, 2, 4, 6 without filling 1, 3, 5 with an empty component in a GridBagLayout using GridBagConstraints?
The example in Java here sets the 5th button to start on column 1, but maybe because the rows above it were set already?
https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

A:
Is there a way to set components in alternating columns 0, 2, 4, 6 without filling 1, 3, 5 with an empty component in a GridBagLayout

No. If a component isn't defined for a cell then basically its size is 0.
The layout can't guess what size you expect the "empty column" to be.
Maybe you can use the "insets" constraint to give space between columns.

A: You can define your GridBagLayout with row heights and column widths
int[]  rowHeights = new int[] { 50, 50, 50};
int[] columnWidths = new int[] { 100, 100, 100, 100, 100};
GridBagLayout layout = new GridBagLayout();
layout.rowHeights = rowHeights;
layout.columnWidths = columnWidths;

Add the components using GridBagConstraint as below
    JPanel panel = new JPanel();
    panel.setLayout(layout);

    JLabel label1 = new JLabel("Label 1");
    JLabel label2 = new JLabel("Label 2");
    JLabel label3 = new JLabel("Label 3");

    panel.add(label1,  new GridBagConstraints(
            0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
            new Insets(0,0, 0, 0), 0, 0));

    panel.add(label2,  new GridBagConstraints(
            2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
            new Insets(0,0, 0, 0), 0, 0));

    panel.add(label3,  new GridBagConstraints(
            4, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
            new Insets(0,0, 0, 0), 0, 0));

redpajama_set_name: RedPajamaStackExchange


text:
Q: PolicyKit daemon disconnected from the bus. Error when starting services without sudo on the super user account Hopefully this will be a quick fix, but I have been having a consistent error whenever I try and start a service on my machine.
Whether it be ssh, rdp or apache2, whenever I try and launch the service using the basic command service ssh start for example I am greeted by an error message in my terminal saying the following:
PolicyKit daemon disconnected from the bus.
We are no longer a registered authentication agent.
Failed to start ssh.service: Message recipient disconnected from message bus without replying
See system logs and 'systemctl status ssh.service' for details.

Running the command with a sudo in front of it seems to fix this issue for ssh, and it seems to "work" at first for the other services on my machine. However upon trying to connect to my webserver or my remote desktop service I am simply unable to connect to them.
Also upon rebooting I am also greeted by a system program problem prompt, and I am not told any information about the error.
I am fairly new to Ubuntu so I am unsure as to what may be causing this issue. if anyone can give me advice I would greatly appreciate it.
These are the error logs given to me by the syslog file: These errors crop up every time i try to launch a service without the sudo command.
Jun 3 17:12:26 xxxspermmonkey420xxx kernel: [ 1402.059083] polkitd[5560]: segfault at 8 ip 00007f6c77c88e36 sp 00007ffc95a7a5a0 error 4 in libpolkit-backend-1.so.0.0.0[7f6c77c79000+18000]
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: polkitd.service: Main process exited, code=dumped, status=11/SEGV
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: PolicyKit daemon disconnected from the bus.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: We are no longer a registered authentication agent.
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: polkitd.service: Unit entered failed state.
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: polkitd.service: Failed with result 'core-dump'.
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4188] error requesting auth for org.freedesktop.NetworkManager.reload: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4189] error requesting auth for org.freedesktop.NetworkManager.settings.modify.hos tname: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4190] error requesting auth for org.freedesktop.NetworkManager.settings.modify.own : Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4191] error requesting auth for org.freedesktop.NetworkManager.settings.modify.sys tem: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4191] error requesting auth for org.freedesktop.NetworkManager.wifi.share.open: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4192] error requesting auth for org.freedesktop.NetworkManager.wifi.share.protecte d: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4193] error requesting auth for org.freedesktop.NetworkManager.network-control: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4194] error requesting auth for org.freedesktop.NetworkManager.enable-disable-wimax: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4194] error requesting auth for org.freedesktop.NetworkManager.enable-disable-wwan: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4196] error requesting auth for org.freedesktop.NetworkManager.enable-disable-wifi: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4196] error requesting auth for org.freedesktop.NetworkManager.sleep-wake: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx dbus[1056]: [system] Activating via systemd: service name='org.freedesktop.PolicyKit1' unit='polkitd.service'
Jun 3 17:12:26 xxxspermmonkey420xxx NetworkManager[1083]: <warn> [1528060346.4197] error requesting auth for org.freedesktop.NetworkManager.enable-disable-network: Authorization check failed: Message recipient disconnected from message bus without replying
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: Starting Authenticate and Authorize Users to Run Privileged Tasks...
Jun 3 17:12:26 xxxspermmonkey420xxx polkitd[5609]: started daemon version 0.105 using authority implementation `local' version `0.105'
Jun 3 17:12:26 xxxspermmonkey420xxx dbus[1056]: [system] Successfully activated service 'org.freedesktop.PolicyKit1'
Jun 3 17:12:26 xxxspermmonkey420xxx systemd[1]: Started Authenticate and Authorize Users to Run Privileged Tasks.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: PolicyKit daemon reconnected to bus.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: Attempting to re-register as an authentication agent.
Jun 3 17:12:26 xxxspermmonkey420xxx gnome-session[4459]: We are now a registered authentication agent.


text:
Q: Getting a std::string or C string from a QString representing an arbitrary filename on Windows I'm using QFileDialog::getOpenFileName() to have the user select a file, but I need the result to be a C string, since I have to pass it to something written in C which uses fopen(). I cannot change this.
The problem I'm finding is that, on Windows/MinGW, using toStdString() on the resulting QString doesn't work well with Unicode/non-ASCII filenames. Trying to open the file based on the std::string fails, because some character set conversion seems to be occurring. Sometimes using toLocal8Bit() to convert works, but sometimes it doesn't.
Consider the following (MinGW) program:
#include <cstdio>
#include <iostream>

#include <QApplication>
#include <QFileDialog>
#include <QFile>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    auto filename = QFileDialog::getOpenFileName();
    QFile f(filename);

    std::cout << "fopen: " << (std::fopen(filename.toStdString().c_str(), "r") != nullptr) << std::endl;
    std::cout << "fopen (local8bit): " << (std::fopen(filename.toLocal8Bit().data(), "r") != nullptr) << std::endl;
    std::cout << "Qt can open: " << f.open(QIODevice::ReadOnly) << std::endl;
}

*

*For a file called ☢.txt, toStdString() works, local8Bit() doesn't.

*For a file called ä.txt, toStdString() doesn't work, local8Bit() does.

*For a file called Ȁ.txt, neither works.

In all cases, though, QFile is able to open the file. I suppose it's probably using Unicode Windows functions while the C code is using fopen(), which, to my understanding is a so-called ANSI function on Windows.  But is there any way to get a "bag of bytes", so to speak, from a QString?  I don't care about the encoding of the filename, I just want something that can be passed to fopen() to open the file.
I've found that using GetShortPathName to get a short filename from filename.toWCharArray() seems to work, but that's very cumbersome, and my understanding is that NTFS filesystems can be told not to support short names, so it's not a viable solution in general anyway.

A: File paths in the non-unicode API of Windows are either parsed in the current ANSI (Microsoft codec) codepage, or in the OEM codepage (see also https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfope). ANSI is the default.
So your question translates to: How can I convert a UTF-8 or UTF-16 string to ANSI or OEM?
There's an answer for the ANSI conversion: How to convert from UTF-8 to ANSI using standard c++
Anyhow, it's important to realize that not all UTF strings can be represented in these more narrow codecs...


text:
Q: Replace value using REGEX with Groovy and SED I have an XML file that contains a "Description" property. I would like to replace the contents of that property with a different description. I am using a SED command within a Groovy script
<VisualElements Description="foo" Title="title"/>

I tried the following line, but it does not replace the value of the "Description" value with the string "bar".
def sedCommand = 'sed -i \'s/Description="([^"]*)"/Description="bar"/g\'  package.appxmanifest' as String

Can someone tell me what is wrong with the above line?
Update: based on Wiktor Stribiżew's comment below, I have updated the command to reflect the latest error

A: You are using sed with a BRE regex (i.e. no -E or -r options), so your ( and ) are parsed as literal parentheses, not a grouping construct. Anyway, you are not using backreferences and replacing the whole match, there is no point keeping the parentheses at all:
def sedCommand = 'sed -i \'s/Description="[^"]*"/Description="bar"/g\'  package.appxmanifest' as String
                                          ^^^^^

will work well.
If you need to use variables, see How do I use variables in a sed command?
The sed command will look as
#!/bin/bash
foo="hello"
echo '<VisualElements Description="foo" Title="title"/>' | \
 sed 's/Description="[^"]*"/Description="'$foo'"/g'

See this demo.


text:
Q: Is it true that $\{x^3+2y^3+3z^3:\ x,y,z\in\mathbb Z\}=\mathbb Z$? It is easy to see that no integer congruent to $4$ or $-4$ modulo $9$ can be written as the sum of three integer cubes. In view of this and Question 331163, I proposed the following conjecture in March 2019.
Conjecture. Every integer $n$ can be written as $x^3+2y^3+3z^3$ with $x,y,z$ integers. That is,
$$\{x^3+2y^3+3z^3:\ x,y,z\in\mathbb Z\}=\mathbb Z.$$
This conjecture has an interesting application. Under the conjecture, my result on Hilbert's Tenth Problem implies that there is no effective algorithm to test for a general polynomial $P(x_1,\ldots,x_{33})$ with integer coefficients whether the diophantine equation
$$P(x_1^{3},\ldots,x_{33}^3)=0$$
has integer solutions.
Quite recently, my PhD student Chen Wang checked my above conjecture seriously. He found that the set
$$\{0,\ldots,5000\}\setminus\{x^3+2y^3+3z^3:\ x,y,z\in\{-30000,\ldots,30000\}\}$$
only contains four numbers: $36,\ 288,\ 2304,\ 4500.$ For example, he obtained that $$3772=(-20027)^3+2\times15936^3+3\times(-2739)^3.$$
Note that
$$288=2^3\times 36,\ \ 2304=4^3\times36,\ \ 4500=5^3\times36.$$
So, to finish the verification of the conjecture for all $n=0,\ldots,5000$, it remains to find $x,y,z\in\mathbb Z$ with $x^3+2y^3+3z^3=36$.
QUESTION. Are there integers $x,y,z$ satisfying $x^3+2y^3+3z^3=36$?

A: Above equation shown below:
$x^3+2y^3+3z^3=n$        ------------$(1)$
Above equation $(1)$ can be written as:
$ax^3+by^3+cz^3=n$
Seiji Tomita has shown that for $(a+b=c)$ there are rational solution's for any '$n$'.
For, $n=36$, $(a,b,c)=(1,2,3)$, the solution is:
$(x,y,z)=[(167/9),(158/9),(-161/9)]$
The above numerical solution is equivalent to:
$(167)^3+2(158)^3+3(-161)^3=26244$
And, 26244= (9)^3*(36)
His web page link is:
     http://www.maroon.dti.ne.jp/fermat

Click on "Computational number theory" & select article # 313.


text:
Q: how to deal with bit fields in Julia when writing a wrapper of C typedef struct {
uint32_t is_bin:1, is_write:1, is_be:1, is_cram:1, dummy:28;
int64_t lineno;
kstring_t line;
char *fn, *fn_aux;
union {
    BGZF *bgzf;
    struct cram_fd *cram;
struct hFILE *hfile;
    void *voidp;
} fp;
htsFormat format;
} htsFile;

how to deal with the bit fields part of htsFile in Julia?
If I am not care about the specific value uint32_t is_bin:1, is_write:1, is_be:1, is_cram:1, dummy:28;, can I just use a Cuint variable to repalce it in julia?

A:
can I just use a Cuint variable to replace it in julia?

Yes, the alignment will be the same. If you do need the values, you can use bitmasks to select the required bit(s).
As a side note, the StrPack package may be of interest for dealing with complicated struct [de]serialization (although I don't think it has built-in bitfield support).

A: You can extract the individual bits using julia'a bitwise manipulation functions (&, >>, etc.) You could define convenience functions like is_bin(x) = (x & 0x01) > 0.


text:
Q: Sync MediaElement to Slider in Windows Store App Im developing an app like media player to  Windows Store using c#. I use C# But I have a problem .
I want to sync MediaElement to slider. For examle the music in the mediaelement and music is playing. I want to see the position of music in the slide bar. For example if music in the 30th , Sliderbar's value is 30.

A: I answered a very similar question already. Please take a look at this answer and let me know if that's what you were looking for! If you need more details, please comment.

A: A msdn tutorial including the implementation of a slider control is provided here. Hope this helps.


text:
Q: Codemagic build process for a Flutter app: Could not find a file named "pubspec.yaml" I am using Codemagic for the iOS build process for a Flutter app.
In the pubspec.yaml I am referring to a package dependency by pointing to a public repository like so:
dependencies:
  flutter:
    sdk: flutter
  flutter_circular_slider:
    git: https://github.com/tomoehlrich/flutter-circular-slider.git

It all works with local debugging and when building an apk with "flutter build apk" on Windows.
Codemagic though keeps giving me the following error message in the build step "Installing dependencies":
== Install Flutter dependencies ==
> flutter packages pub get
Resolving dependencies...
Could not find a file named "pubspec.yaml" in https://github.com/tomoehlrich/flutter-circular-slider.git 5d6d0c54e93766b27d30707bf20042b26894561c.pub

finished with exit code 1

Build failed :|Failed to install dependencies

I had Codemagic working before. The difference now to the working version was that I was referencing a different repository on Github.
I am trying to figure out why the build process cannot find the pubspec.yaml in https://github.com/tomoehlrich/flutter-circular-slider.git but in another fork of the same flutter package on Github.
Any hints are highly appreciated.

A: It seems that "resolved-ref" in pubspec.lock for the slider package was an outdated reference.
A new generation of pubspec.lock, sync to GitHub and start a new build process in Codemagic did the trick.


text:
Q: A detail in the construction of the coarse index of a Dirac operator in "Roe: An Index Theorem on Open Manifold, I" Hi,
I'm currently wreading "Roe: An Index Theorem on Open Manifolds, I, J. Differential Geometry 27 (1988), p. 87-113" and there is a detail in the construction of the coarse index of a Dirac operator that I do not understand.
In Section 4 he explains the construction of abstract indices: Suppose we are given an algebra A with unit and an ideal $B \subset A$. Let M and N be finite, projective right A-modules and let $P: M \to N$ be A-linear (this is bold, because this is the thing which I do not understand later when we look at the Dirac operator). P is called abstractly elliptic if there is a parametrix $Q: N \to M$ such that $Im(QP-1) \subset M \otimes B$ and $Im(PQ-1) \subset N \otimes B$, i.e. P is an isomorphism after tensoring with A/B. He then goes on and explains how to get an index $\operatorname{Ind}(P) \in K^{alg}(B)$.
In Section 7 he then uses this construction to get a coarse index of a Dirac operator: Let $S \to M$ be a Clifford bundle, equipped with a grading $\eta$ and let D be the corresponding Dirac operator. In Lemma 7.6 he shows then (under the assumption of bounded geometry) that the operator D is abstractly elliptic between the $\mathcal{U}(S)$-modules given by the eigenprojections $(1+\eta)/2$ and $(1-\eta)/2$, i.e. has an index in $K^{alg}(\mathcal{U}_{-\infty}(S))$.
Now the thing that I do not understand is that for $D_+: S_+ \to S_-$ being abstractly elliptic means that $D_+$ is, among other things, $\mathcal{U}(S)$-linear. This algebra $\mathcal{U}(S)$ is the algebra of all uniform operator, i.e. all operator $L: C_c^\infty(S) \to C^\infty(S)$ which have for a fixed k (the order of L) a continuous extension to a operator $H^r(S) \to H^{r-k}(S)$ for each r (this extensions must also be a quasilocal operator, but I do not think that this matters here), where $H^r$ are the Sobolev spaces. $\mathcal{U}_{-\infty}(S)$ are the operator of order $-\infty$.

Why does the Dirac operator, resp. just $D_+$ and $D_-$, commute with all of $\mathcal{U}(S)$? Or do I just not correctly understand the construction?

A: This is a "left and right" issue.  The point is that if $A$ is an algebra, the operation of left multiplication by a fixed $a\in A$ (considered as a map $A\to A$) is linear as a map of right $A$-modules.


text:
Q: Finding location of company from website First, thanks for the help I just started learning to code a few days ago, so I appreciate the help!
so basically I have a list of company urls and want to find where they are located. What I've been thinking of doing was using urllib2 and BeautifulSoup to get all of the text from the urls and then searching through that text to find either California, Massachusetts, new york, etc and having it print out whichever one it finds into a document I can put into excel. So far I've written the code below which gives me a set of text, but I have no idea how to search it, how to do it with multiple urls, or how to print that information into an Excel-readable format.
Thank you!
import urllib2
import re
from bs4 import BeautifulSoup

links = urllib2.urlopen('http://www.coolcomposites.com/')
html = links.read()
soup = BeautifulSoup(html, "html.parser")
locations = ["Boston", "MA"]
file_text = soup.get_text()
print (file_text)

A: You need to iterate through the locations list and check if each entry exists in file_text.
for loc in locations:
  if loc in file_text:
    print ("Found location")
  else:
    print ("Location not found")

Watch Out
1. Capitalization
Stick with one representation of locations. Either everything is lower case, upper or upper first then lower etc. Point is, don't mix it up because it the above implementation is not case sensitive so MA != ma != Ma != mA.
So say you choose lower case for locations, convert file_text to lower case as well.
2. Mid point detection
In locations, you included MA. This will be detected as well in any text that consists of MA regards of its location. Think of possible ways to overcome this problem.


text:
Q: Get subclass content from object I have the following classes
public enum Category { foo, foo1, foo2 }

public class Event
{

    public DateTime Timestamp { get; set; } = DateTime.Now;
    public string GameTime { get; set; }
    public string Content { get; set; }
    public Person Author { get; set; }
    public Category Category { get; set; }

}

and
public class MemberEvent : Event
{
    public Member Person { get; set; }
}

The object is created correctly, but if I want to call "Person", this is not displayed to me. If I have a var match, I can call for example match[0].Timestamp but not match[0].Person. The Event object is stored in a List, therefore also the index. I feel I'm missing something simple.
UPDATE: The Code that create the Object
var match = SessionController.Instance.Current;

DataTable dt = dataGrid.ItemsSource as DataTable;

        foreach (System.Data.DataRow item in dt.Rows)
        {
                var memberFoo = new MemberEvent();
                memberFoo.Category = Category.Warning;
                memberFoo.Time = item["Time"].ToString();
                var person = new Person();
                person.FirstName = item["FirstName"].ToString();
                person.LastName = item["LastName"].ToString();
                var passport = new Passport();
                passport.Active = true;
                passport.PassNumber = item["Pass"].ToString();
                passport.Player = person;
                memberFoo.Person = passport;
                match.Match.Events.Add(memberFoo);
        }

        SessionController.Instance.Current = match;

A: You will have to cast your Event into a MemberEvent if you want to access the Person property. It is not possible to get the property from Event.
List<Event> myEvents = GetMyEvents();
var myMemberEvent = (MemberEvent)myEvent[0];

It can cause an exception if it can't convert to MemberEvent.

A: Cast your instance to the expected type and test for null to guard for the unexpected:
var memberEvent = match[0] as MemberEvent;
if (memberEvent != null)
{
   Console.WriteLine(memberEvent.Person)
}


text:
Q: Will FPGA synthesis tools ignore unused modules? In a VHDL/Verilog design, is it a bad practice to define several (related) modules in the same file?
Will the Vivado synthesis tool be 'smart' enough to not book FPGA resources for unused modules?

A: Unlike software where the compiler will sometimes keep code around that isn't actually called (particularly for things like libraries), this isn't the case for HDL designs.  This is because HDL isn't "executed" like software, instead it gets converted to a netlist, which defines components and the connections between them.  So an HDL module never consumes any resources.  What does consume resources are instances.  A module that is never instantiated simply does not exist in the synthesized design and hence consumes no resources.  Similarly, if you have multiple instances of the same module, each instance will consume more resources.  For example, four instances of one module will consume four times the logic resources of one instance (ignoring optimizations, etc.).
Additionally, the tools will take steps to optimize the design and remove unnecessary logic.  Inputs that are tied off to constant values will be removed through "constant propagation", which will simplify logic to remove any connections whose value can be determined to be constant during synthesis.  Similarly, outputs that do not drive anything are removed.  Also, identical logic with identical inputs will also be merged.

A: Vivado has a specific property top that you can use to set the top-level module. From there, the elaboration process looks recursively down the hierarchy collecting required modules to complete the design. Any module compiled but not instantiated is ignored.
I believe there are a number of other mechanisms used to figure out which modules to include in the simulation or synthesis environment.


text:
Q: How is Spring Boot aware of Heroku's DATABASE_URL config var? Short story:
How exactly does Spring Boot parse the DATABASE_URL config var? Setting an environment property with same name on my local PC has no effect. Which classes in Spring Boot library are involved? Full text search on DATABASE_URL returns nothing.
Long story:
I have recently deployed a simple Spring Boot + JPA application to Heroku. My heroku was already configured with the Postgres add-on.
During my first deployment I only wanted to confirm, that the application builds and starts correctly. To my surprise though, the application immediately connected to the Postgres database configured in Heroku's DATABASE_URL config var:
2018-11-30T09:28:51.054688+00:00 app[web.1]: 2018-11-30 09:28:51.054  INFO 4 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect

This leads me to the questions already posted above.
I am using Spring boot 2.1.0., a simple app created by Spring Initializr, with Web + JPA + H2 + PostgreSQL. H2 is included, because:

*

*I want to run unit tests with embedded H2

*most of time, I want to run my application locally with embedded H2, but sometimes, I want to switch to Heroku's Postgres, so that I can verify some DB specific stuff (e.g. migrations)

A: Spring is not aware of DATABASE_URL (as far as I know). But it does detect and automatically use SPRING_DATASOURCE_URL, which the Heroku Java buildpack sets at runtime.
You can read more about this env var in the Heroku docs on Connecting to Relational Databases on Heroku with Java

A: To be able to switch easily between h2 and heroku, one could have 2 configurations files
The h2 properties files named application-h2.properties :
spring.profiles.active=h2
spring.datasource.url= # H2 URL of the database.
spring.datasource.driver-class-name=# H2 JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.username= # Login username of the database.

Activated by setting the h2 profile to on when running the spring boot app:
java -jar -Dspring.profiles.active=h2 myApplication.jar

The heroku properties files named application-heroku.properties :
spring.profiles.active=heroku
spring.datasource.url= # herokuURL of the database.
spring.datasource.driver-class-name=# herokuJDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.username= # Login username of the database.

Activated by setting the heroku profile to on when running the spring boot app:
java -jar -Dspring.profiles.active=heroku myApplication.jar

A: I will answer my own question, to amend the accepted answer with more details about environment properties set by Heroku.
Assuming, that your Heroku application contains environment variable:

*

*DATABASE_URL = postgres://username:password@host:port/database
Heroku will automatically provide following environment variables (which you can use e.g. in your favorite JDBC based SQL client):

*

*JDBC_DATABASE_URL = jdbc:postgresql://host:port/database?user=username&password=password&sslmode=require

*JDBC_DATABASE_USERNAME = username

*JDBC_DATABASE_PASSWORD = password
And additionally those, that get picked up by Spring Boot automatically (which you can use to modify your local Spring boot profile:

*

*SPRING_DATASOURCE_USERNAME = same as JDBC_DATABASE_USERNAME

*SPRING_DATASOURCE_PASSWORD =  same as JDBC_DATABASE_PASSWORD

*SPRING_DATASOURCE_URL = same as JDBC_DATABASE_URL
I observed this, by using a simple REST endpoint:
@RequestMapping("/env")
public @ResponseBody Map<String, String> env() {
    return System.getenv();
}

Be careful, not to make the same mistake as I did: DATABASE_URL starts with postgres, while JDBC prefix for Postgres is postgresql. Using SPRING_DATASOURCE_URL with prefix jdbc:postgres:// will lead to following error:

Driver org.h2.Driver claims to not accept jdbcUrl, jdbc:postgres://....


text:
Q: Cannot test WebClient exception situation I use Spring WebClient and write a test by following this page.
Everything is ok except from the exception test. I tried to use many different exception classes, but each time I get:

java.lang.AssertionError: Expecting a throwable with cause being an instance >of:java.lang.RuntimeException but current throwable has no cause.

The test method is here:
@Test
void throwsProductServiceExceptionWhenErrorStatus() throws JsonProcessingException {
    server.enqueue(
            new MockResponse()
                    .setResponseCode(500)
                    .setHeader("content-type", "application/json")
                    .setBody("{}"));

    assertThatThrownBy(() -> client.findByName("flower"))
            .hasCauseInstanceOf(RuntimeException.class);
    // I also tried many other exception types e.g. JsonProcessingException
}

Here is my WebClient method that I want to create exception test:
private String fetchData(String title, String uri) {
    // make GET call with WebClient.get and use a Mono of String to get the response as JSON string
    return webClient
            .get()
            .uri(uri, title)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is5xxServerError,
                    error -> Mono.error(new RuntimeException(ERROR_WHEN_FETCHING_DATA)))
            .bodyToMono(String.class)
            .block();
}

Any idea?


text:
Q: Remove extra right margin when using alert-dismissible Adding alert-dismissible adds a margin to the whole alert box, which I don't like:

                Hello!

                Bla bla bla

        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            ×
        </button>

As you can see in the JSFiddle, the video doesn't take the full width of the alert, but stays too far from the right side. Removing alert-dismissible fixes this, but I want this functionality.

A: Just reset its padding???
.alert.alert-dismissible {
    padding-right: 1.25rem;
}

If you're building custom theme with Bootstrap SASS files, you can do something like:
.alert {
    &.alert-dismissible {
        padding-right: @alert-padding-x;
    }
}

demo: https://jsfiddle.net/davidliang2008/05puear4/2


text:
Q: Sandbox Source Tracking does not activate I have enabled source tracking in Developer and Developer Pro sandboxes in the production org, but source tracking commands still throw an error even after a sandbox refresh.
Some details: we have a master sandbox(developer) with some test data already created and we refresh/create our sandboxes from it. After I activated the Source Tracking in Dev and Dev Pro Sandboxes, I refreshed my sandbox from the master sandbox(both are developer sandboxes), re-authorized the org in my VSC and also restarted VSC, but I am still getting the error when I try to reset the tracking:
PS C:\Users\Novarg\Documents\VSCode\salesforce-sfdx> sfdx force:source:tracking:reset
WARNING: apiVersion configuration overridden at "56.0"
WARNING: This operation will modify all your local source tracking files. The operation can have unintended consequences on all the force:source commands. Are you sure you want to proceed (y/n)?: y
ERROR running force:source:tracking:reset:  This command can only be used on orgs that have source tracking enabled, such as sandboxes and scratch orgs.

My guess is that we did not have source tracking activated in the master sandbox, so a refreshed sandbox from it also did not have it enabled. I also checked the documentation, but it does not say anything about refreshing sandboxes from an existing sandbox. The only requirement is to create/refresh a sandbox after activating this feature which I have done.
Is it documented somewhere that we need to refresh or create a sandbox from production or does it just take a while to register and I should try refreshing again tomorrow?


text:
Q: Twilio how to get only messages sent by a Messaging Service I am using the Twilio messaging service to send from multiple numbers.
I want to get messages that were sent from that messaging service.
I am trying to use stream, as I don't want thousands of messages
for each call.
Is there a way to get only messages that were sent out using a
particular messaging service?
$searcher = new TwilioLogRetriever;
$searcher->listMessagesForMessagingService('MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

TwilioLogRetriever
<?php
use Twilio\Rest\Client;

class TwilioLogRetriever {
    function listMessagesForMessagingService($messagingServicesSid) {
        $client = new Client(Configure::Read('twilio.accountSid'), Configure::read('twilio.authToken'));
        $once = false;
        $n = 0;
        // Try specifying 'from' (just guessing)
        foreach ($client->messages->stream(['from' => $messagingServicesSid]) as $message) {
            ++$n;
            //echo $message->body . "\n";
            $data = [
                'from' => $message->from,
                'to' => $message->to,
                'direction' => $message->direction,
                'messagingServiceSid' => $message->messagingServiceSid,
                'numMedia' => $message->numMedia,
                'numSegments' => $message->numSegments,
                'price' => $message->price,
                'priceUnit' => $message->priceUnit,
                'sid' => $message->sid,
                'status' => $message->status,
                'body' => $message->body,
            ];
            $data['dateCreated'] = $message->dateCreated->format('Y-m-d H:i:s');
            $data['dateUpdated'] = $message->dateUpdated->format('Y-m-d H:i:s');
            $data['dateSent'] = $message->dateSent->format('Y-m-d H:i:s');

            if ( ! $once ) {
                print_r($message);
                $once = true;
            }
        }
        $this->out(__METHOD__. " Found $n messages." );
    }

    function out($message ) {
        echo $message . "\n";
    }

}


text:
Q: returning dictionary of generator the most efficient way I have written this function that returns a dictionary, I think either by itertools or by just using yeild i can return dictionary but I have never done that in case of a dictionary
def configDb():
    """ Reads git global config file

        Returns:
            config(dict): git config settings
    """
    # Read git config file
    configFile, _ = execGitCommand('git config --list')
    config = {}
    for line in (each for each in configFile.split("\n") if each):
        config[line.split("=")[0]] = line.split("=")[-1]

    return config

how can I make this function act in a way I do not have to call like configDb() but instead just configDb[key] should give me value ?

A: Dictionaries can't be generatored, but you can yield key-value tuples
def configDb():
    """ Reads git global config file

        Returns:
            config(dict): git config settings
    """
    # Read git config file
    configFile, _ = execGitCommand('git config --list')
    config = {}
    for line in (each for each in configFile.split("\n") if each):
        yield line.split("=")[0], line.split("=")[-1]

A: A partial config file is hardly useful, so there doesn't seem to be much point in a "generated dictionary".
def configDb():
    """ Reads git global config file

        Returns:
            config(dict): git config settings
    """
    # Read git config file
    configFile, _ = execGitCommand('git config --list')
    rows = (line.split("=") for line in configFile.splitlines())
    return dict(row for row in rows if len(row)==2)


text:
Q: Function slideToggle not detecting the previous open/close state of the div script only javascript Function slideToggle not detecting the previous open/close state of the div script only javascript because in jquery no problem but I only want javascript.
When I click on the second button the div opens and this closes right away as the script does not include detect the state I think but I do not see how to modify the javascript script to prevent the bug.
I want each button to open and close its own div.
current result :
https://jsfiddle.net/vincent1890/5fje4zwv/2/

    <!DOCTYPE html>

            <meta charset="UTF-8">
            <link rel="stylesheet" type="text/css" href="css.css">

                <button class="bouton-deplier" id="mbtn" onclick="slideToggle('mdiv', 50);">+ Options autres</button>
                <button class="bouton-deplier" id="mbtn2" onclick="slideToggle('mdiv2', 100);">+ Optionnel (Telephonie Audioconf)</button>

                        Uid (User):
                        <input type="text" id="ChoisirUid" onfocus="this.value=''" onchange="chg_item()">

                        Num Tel (User):
                        <input type="text" id="ChoisirTelNumber" onfocus="this.value=''" onchange="chg_item()">

                        Nom Prenom :
                        <input type="text" id="ChoisirNomPrenom" onfocus="this.value=''" onchange="chg_item()">

A: HTML

  <button id="btn1" class="btn" onclick="clickHandler('first')">First tab</button>
  <button id="btn2" class="btn" onclick="clickHandler('second')">Second tab</button>

Hello

World!

JavaScript
function clickHandler(id) {
  toggle("data");

  const div = document.getElementById(id);
  div.classList.add("shown");
  div.classList.remove("hidden");
}

function toggle(className) {
  const elements = document.getElementsByClassName(className);

  for (let i = 0; i < elements.length; i++) {
    const elm = elements[i];
    if (elm.classList.contains("shown")) {
      elm.classList.remove("shown")
      elm.classList.add("hidden")
    }
  }
}

This handler changes every element currently shown to hidden, then executes the clickHandler and shows the button only which was clicked.
You can add more css to this for better visuals.
Check out this JSFiddle

A: You can do like this with jquery

$(".bouton-deplier").click(function() {
  var btnID = $(this).attr('id');

  if ($(".textContent:visible").is(':visible')) {
    $(".textContent:visible").slideUp(0, function() {
      $("." + btnID + ".textContent").slideDown("slow");
    });
  } else {
    $("." + btnID + ".textContent").slideDown("slow");
  }
});
        .header {
          padding: 10px 16px;
          background: #555;
          color: #f1f1f1;
          font-size: 0.835em;
          text-transform: uppercase;
          letter-spacing: 0.125em;
          font-weight: bold;
        }

        /* Some Generic styles */
        body {
          text-align: center;
          font-family: "Open Sans", Helvetica, Arial, sans-serif;
          color: #444;
          line-height: 1.6;
        }
        /* CSS styles "+ OPTIONS ..." */
        .bouton-deplier {
            text-decoration: none;
            color: #fff;
            background: #000;
            padding: 5px 10px;
            cursor: pointer;
        }
        .montexte {
            padding: 10px 10px 20px 10px;
        }

        .mbtn {
            display:none;
            height: 60px;
            margin-top: 0px;
            border-radius: 0px;
            font-weight: bold;
            text-align: center;
            overflow-y: hidden;
            background-color: #ef1;
            margin-bottom: 0em;
            color: rgba(0, 0, 0, .65);
        }
        .mbtn2 {
            display:none;
            height: 60px;
            margin-top: 0px;
            border-radius: 0px;
            font-weight: bold;
            text-align: center;
            overflow-y: hidden;
            background-color: #ef1;
            margin-bottom: 0em;
            color: rgba(0, 0, 0, .65);
        }

            <button class="bouton-deplier" id="mbtn">+ Options autres</button>
            <button class="bouton-deplier" id="mbtn2">+ Optionnel (Telephonie Audioconf)</button>

                    Uid (User):
                    <input type="text" id="ChoisirUid" onfocus="this.value=''" onchange="chg_item()">

                    Num Tel (User):
                    <input type="text" id="ChoisirTelNumber" onfocus="this.value=''" onchange="chg_item()">

                    Nom Prenom :
                    <input type="text" id="ChoisirNomPrenom" onfocus="this.value=''" onchange="chg_item()">


text:
Q: Creating an array of JSON objects from another array of JSON objects I have a JSON array like this:
[{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}]

I want to parse this and create a new array of objects which only have non-blank attributes without IDs, i.e:
[{FirstName:"John", SecondName:"Smith"},
{Company:"SomeComp", SecondName:"Kane"},
{Company:"Random", FirstName:"Tom"}]

What is the best way of doing this in Javascript?

A: You can use map

The map() method creates a new array with the results of calling a
  provided function on every element in this array.

var companies = [{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}];

// This returns a new array
var newArray = companies.map(function(item) {
     var obj = {};
     for(var prop in item) {
          if (item[prop] !== "" && prop !== "id" ) {
              obj[prop] = item[prop];
          };
     }
     return obj;
});

console.log(newArray);

A: This should do it
var input = JSON.parse("<YOUR JSON HERE>");
var output = [];
input.forEach(function(item) {
     delete item.ID;
     for (var prop in item) {
         if (item.hasOwnProperty(prop) && item[prop] === "") {
              item[prop] = undefined;
         }
     }
output.push(item);
});


text:
Q: Carbon today/tomorrow instead of in x hours I'm using Carbon to modify dates in a project. Now I need get the date as today, tomorrow etc. so I tried it with:
\Carbon\Carbon::enableHumanDiffOption(\Illuminate\Support\Carbon::ONE_DAY_WORDS);

$date->diffForHumans();

But for today and tomorrow I receive string like: In 5 hours and not tomorrow.
For today i receive: 16 hours ago and not today.
The date is from an mysql date column, eg.: 2018-05-29.
I read that the needed functionality is currently only available for en and fr but also with Carbon::setLocale('en'); i don't receive the needed string.
Using the latest version.

A: as far as Carbon is concerned I haven't seen diffForHumans() returning as Today or Tomorrow. But there is an hack to fulfil your requirements
$now = Carbon::now();
$future = $now->addDays(30);
echo $now->diffInDays($now->copy()->addDay());

this will return 1 if when dates are of tomorrow, and return 0 when dates are of today so you can now manage it with a simple if statement. For online workaround you can check carbon APIs here


text:
Q: Selenium: "DevTools Request: 127.0.0.1:12583/json/version failed" upon instantiation When I create a new chrome driver in Selenium while  Google Chrome is already running AND I am referencing the users settings/data (via user-data-dir). A new Chrome window will open, but my application will hang. The ChromeDriver console will display the following error each second: DevTools Request: 127.0.0.1:12585/json/version. DevTools request failed
Screenshot:
Code to instantiate the driver:
        ChromeDriverService driverService = ChromeDriverService.CreateDefaultService();
        //driverService.HideCommandPromptWindow = true;
        driverService.EnableVerboseLogging = true;

        string path = Environment.ExpandEnvironmentVariables("%LOCALAPPDATA%\\Google\\Chrome\\User Data");

        ChromeOptions options = new ChromeOptions();
        options.AddArguments("user-data-dir=" + path);
        options.AddArguments("--start-maximized");
        options.AddArguments("--disable-extensions");

        IWebDriver driver = new ChromeDriver(driverService, options);

This will work perfectly fine in every instance if I do not try and load user settings/data. If I am trying to load user setting/data it will only work if there is no instance of Chrome running on the device already.
Versions:

*

*Selenium v 2.47.0

*ChromeDriver v 2.16.333243

*Chrome v44.0.2403

What can I do to resolve this?

A: If anyone was looking for answer like me;
https://bugs.chromium.org/p/chromedriver/issues/detail?id=2443

This behavior is by design. Two instances of Chrome can't use the same user-data-dir at the same time. Otherwise they would try to update the same set of files and cause corruptions. So if an instance is already running, attempting to start another instance using the same user-data-dir will cause the second instance to ask the first instance to open a new window, and then the second instance exits.


text:
Q: adrianclay/xbrl composer I need to use adrianclay/xbrl composer to parse the XBRL and IXBRL files with PHP and this composer have a problem, can help me anyone to install and use this composer? or suggest me better composer for parse xbrl and ixbrl files in PHP?
Thanks


text:
Q: Using \Mathsmaller in math display mode makes the character appear to the right of the symbol itstead of below it I am trying to use \prod in math display mode but it appears large (larger than I want it to be) but when I use \mathsmaller from the relsize package the letter appears on right side of it instead of below. Is there any way to make the symbol smaller while the character remains below the symbol?

A: I don't know the package you mention and you didn't provide an example but using \mathop around the construction will revert to the operator limits positioning.
 \mathop{\mathsmaller.....}_0^n

A: For consistency, define a new math operator to be set in \textstyle using amsmath's \DeclareMathOperator*:

\documentclass{article}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath
\DeclareMathOperator*{\sProd}{\textstyle\prod}
\usepackage{relsize}% http://ctan.org/pkg/relsize
\begin{document}
\[
  \prod_{i=1}^{\infty}\ %\frac{1}{i} =
  {\mathsmaller \prod_{i=1}^{\infty}}\ %\frac{1}{i} =
  \sProd_{i=1}^{\infty} %\frac{1}{i}
\]
\end{document}


text:
Q: Grandchildren component selection or Reusing code in components I have an angular 6 site that displays financial reports for end users.  each "report" is made up of a number of "widgets." I end up repeating a lot of code for each widget.  It seems like i should be able to reduce the amount of code i am typing.
I have searched for examples, but keep getting results for how to pass variables between components rather than what I am trying to do.
what I have:

{{section3title}}

            <app-assetbyentity
              [jsondata] = 'section3data'>
            </app-assetbyentity>

what I would like to achieve:
    <widget
        [title] = 'section3tile'>
    <app-assetbyentity
        [jsondata] = 'section3data'>
    </app-assetbyentity>
    </widget>

I end up including the

{{section3title}}

code 40 times throughout the site. I have to go back and change a lot of code whenever I made a change to the overall look of each report.  I think I want to determine the grandchild component from the parent, but can't find the right google terms to find relevant examples. if anyone will point me in the right direction, i would appreciate it.


text:
Q: Release memory from loaded xml? For example, if you load a xml and use it for whatever reason:
XDocument doc = XDocument.Load("my.xml");

Now that you have finished using it and want to release any memory used by it, initally i tought that setting it to null would do the job but it does not, so what is the proper way to release the used memory if that is possible ?

A: You are doing the proper thing. Let the GC worry about when it collects as it will when there's pressure.

A: The proper way is to simple stop using doc.  The garbage collector will clean up the memory the next time it's invoked and determines doc is no longer referenced by your code.
If doc is a local the JIT will determine the last point it's used and make it eligable for collection at that point.  There is no need to null it out.  Raymond Chen has an excellent blog article explaining how this works

*

*http://blogs.msdn.com/b/oldnewthing/archive/2010/08/10/10048149.aspx


text:
Q: OkHttp proxy settings I have to setup a proxy to send a JSON using POST, using proxyHost and proxyPort.
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  Proxy proxyTest = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy", proxyPort));

  OkHttpClient client = new OkHttpClient()
  .proxy(proxyTest)
  .build();
  //OkHttpClient.Builder builder = new OkHttpClient.Builder();
  //builder.proxy(proxySAP);
  //client.setProxy(proxySAP)
  //OkHttpClient client = builder.build();;

  String post(String url, String json) throws IOException {

    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

When i try to use the proxyTest that I've saw on some answers here it points an error:

The method proxy() in the type OkHttpClient is not applicable for the
  arguments (Proxy)

Iam using the OKHTTP 3.3.1(okhttp3)
My question is, what should I do? I did some tests like this:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
  builder.proxy(proxyTest);
  client.setProxy(proxyTest)
  OkHttpClient
  client = builder.build();

But nothing works so far.
Thanks for your time!

A: SOCKS5 Auth example
I think it's the easiest working soulution. But it seems to me that it can be not 100% safe. I took this code from this code from here and modified it because my proxy's RequestorType is SERVER.
Actually, java has a strange api for proxies, you should to set auth for proxy through system env ( you can see it from the same link)
final int proxyPort = 1080; //your proxy port
final String proxyHost = "your proxy host";
final String username = "proxy username";
final String password = "proxy password";

InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);

Authenticator.setDefault(new Authenticator() {
  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
    if (getRequestingHost().equalsIgnoreCase(proxyHost)) {
      if (proxyPort == getRequestingPort()) {
        return new PasswordAuthentication(username, password.toCharArray());
      }
    }
    return null;
  }
});

OkHttpClient client = new OkHttpClient.Builder()
        .proxy(proxy)
        .build();

A: Found the solution:
  OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();

If we use the builder to input the proxy, it will work like a charm =D

A: okhttp version:3.11.0. SOCKS proxy example
String hostname = "localhost"/*127.0.0.1*/;
int port = 1080;
Proxy proxy = new Proxy(Proxy.Type.SOCKS,
        new InetSocketAddress(hostname, port));

OkHttpClient client = new OkHttpClient.Builder()
        .proxy(proxy)
        .build();


text:
Q: Configuring analyzer in elastic search I wrote below program to understand how elastic search could be used to do full text search. Here when I search for individual words it works right but I want to search for combinations of words and that is not working.
package in.blogspot.randomcompiler.elastic_search_demo;

import in.blogspot.randomcompiler.elastic_search_impl.Event;

import java.util.Date;

import org.elasticsearch.action.count.CountRequestBuilder;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import com.fasterxml.jackson.core.JsonProcessingException;

public class ElasticSearchDemo
{
    public static void main( String[] args ) throws JsonProcessingException
    {
        Client client = new TransportClient()
        .addTransportAddress(new InetSocketTransportAddress("localhost", 9301));

        DeleteResponse deleteResponse1 = client.prepareDelete("chat-data", "event", "1").execute().actionGet();
        DeleteResponse deleteResponse2 = client.prepareDelete("chat-data", "event", "2").execute().actionGet();
        DeleteResponse deleteResponse3 = client.prepareDelete("chat-data", "event", "3").execute().actionGet();

        Event e1 = new Event("LOGIN", new Date(), "Agent1 logged into chat");
        String e1Json = e1.prepareJson();
        System.out.println("JSON: " + e1Json);
        IndexResponse indexResponse1 = client.prepareIndex("chat-data", "event", "1").setSource(e1Json).execute().actionGet();
        printIndexResponse("e1", indexResponse1);

        Event e2 = new Event("LOGOUT", new Date(), "Agent1 logged out of chat");
        String e2Json = e2.prepareJson();
        System.out.println("JSON: " + e2Json);
        IndexResponse indexResponse2 = client.prepareIndex("chat-data", "event", "2").setSource(e2Json).execute().actionGet();
        printIndexResponse("e2", indexResponse2);

        Event e3 = new Event("BREAK", new Date(), "Agent1 went on break in the middle of a chat");
        String e3Json = e3.prepareJson();
        System.out.println("JSON: " + e3Json);
        IndexResponse indexResponse3 = client.prepareIndex("chat-data", "event", "3").setSource(e3Json).execute().actionGet();
        printIndexResponse("e3", indexResponse3);

        FilterBuilder filterBuilder = FilterBuilders.termFilter("value", "break middle");

        SearchRequestBuilder searchBuilder = client.prepareSearch();
        searchBuilder.setPostFilter(filterBuilder);

        CountRequestBuilder countBuilder = client.prepareCount();
        countBuilder.setQuery(QueryBuilders.constantScoreQuery(filterBuilder));

        CountResponse countResponse1 = countBuilder.execute().actionGet();
        System.out.println("HITS: " + countResponse1.getCount());

        SearchResponse searchResponse1 = searchBuilder.execute().actionGet();
        SearchHits hits = searchResponse1.getHits();
        for(int i=0; i<hits.hits().length; i++) {
            SearchHit hit = hits.getAt(i);
            System.out.println("[" + i + "] " + hit.getId() + " : " +hit.sourceAsString());
        }

        client.close();
    }

    private static void printIndexResponse(String description, IndexResponse response) {
        System.out.println("Index response for: " + description);
        System.out.println("Index name: " + response.getIndex());
        System.out.println("Index type: " + response.getType());
        System.out.println("Index id: " + response.getId());
        System.out.println("Index version: " + response.getVersion());
    }
}

The issue I am facing is that when I search for "break middle" it returns nothing, expectation is that it should return the 3rd event.
I understand that I need to configure a different analyzer rather the default one to make it index appropriately.
Could someone please help me in understanding how to do that. Some complete example would to great to have.

A: The problem is caused because you are using the Term filter:
FilterBuilder filterBuilder = FilterBuilders.termFilter("value", "break middle");

A Term filter doesn't analyse the data in the query string - so Elasticsearch is looking for the exact string "break middle".
However the third document will probably have been broken down by ES into individual terms as follows:
Agent1
went
on
break
in
the
middle
of
a
chat

to fix the issue, use a filter or query that analyses the string you're passing - for example use a Query_String query or Match query.
For example:
QueryBuilder qb = QueryBuilders.matchQuery("event", "break middle");

or:
QueryBuilder qb = QueryBuilders.queryString("break middle");

See the Java API documentation for Elasticsearch for more info.


text:
Q: IP to country in counter report in drupal Hi all
I am new to drupal making site on drupal. In this I want to show countr report like fiddzit live trafic feed. I want to convert counter report style according to that and show on every page.
But in counter report it show according to IP. How can I convert IP into country
Any help will be appriciated

A: A good place to start is looking through the existing modules and see if there is one that meets your needs. It just happens there are at least two modules that fit your description:

*

*IP-based Determination of a Visitor's Country

*IP to Country (on the module description page you will even find a list of other similar modules).

So it looks like you just need to do a bit of research and find the best module for you. Good luck!

A: Take a look at Smart IP. It allows for Device Geolocation, with free and paid geographic data options and there is a code snippet with an example of converting an IP to a country. From the Smart IP project page:
<?php $smart_ip_session = smart_ip_session_get('smart_ip'); ?>
<?php if ($smart_ip_session['location']['country_code'] == 'AR'): ?>

Argentina HTML content specific

<?php elseif ($smart_ip_session['location']['country_code'] == 'UY'): ?>

Uruguay HTML content specific

<?php else: ?>

Fallback default content.

<?php endif; ?>


text:
Q: Убрать звук обновления в .NET WebBrowser - C++ Не могу перевсти данный код с C# в C++ или C++/CLI
Цель в заголовке.
    const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
const int SET_FEATURE_ON_PROCESS = 0x00000002;

[DllImport("urlmon.dll")]
[PreserveSig]
[return: MarshalAs(UnmanagedType.Error)]
static extern int CoInternetSetFeatureEnabled(int FeatureEntry,
                                              [MarshalAs(UnmanagedType.U4)] int dwFlags,
                                              bool fEnable);

static void DisableClickSounds()
{
    CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,
                                SET_FEATURE_ON_PROCESS,
                                true);
}

A: Переписал ваш код на C++/CLI:
using namespace System;
using namespace System::Runtime::InteropServices;

[DllImport("urlmon.dll")]
int CoInternetSetFeatureEnabled(int FeatureEntry, [MarshalAs(UnmanagedType::U4)] int dwFlags, bool fEnable);

public ref class PInvoke abstract sealed
{
private:
literal int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
literal int SET_FEATURE_ON_PROCESS = 0x00000002;
public:
static void DisableClickSounds() {
    CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS, SET_FEATURE_ON_PROCESS, true);
};

};

Вызывайте метод так
PInvoke::DisableClickSounds();

A: Ну вот же ваша функция.
Вы должны подключить
#include "urlmon.h"

и вызвать просто вот точно так же
CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,
                            SET_FEATURE_ON_PROCESS,
                            true);

Как ни странно, код ничем не отличается, даже константы определены так, как надо.
Не забудьте прилинковать urlmon.lib.


text:
Q: Strange Blank Space on Left of Main Content in IE Hello i dont know if this is related to a previous question that i asked on here
but it would seem so. I thought it bets to ask a new question as that last question was resolved.
You can view my website here
As you can see the center coloum is pushed over to the right on Internet Explorer. It seems ok on other browsers. I was hoping it was just the table width but its not as you can see if you view any other content. Ive been looking into it but ive not had much luck.
Can anyone see why this is so in Internet Explorer? If i can sort this then i think that after 7 years my website might actually be considered 'done' and i can get my life back so all help would be much appreciated.
Thanks

A: This is due to the Internet Explorer Box model.  The padding is inside the content rather than outside.  see - http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug.
Remove the padding-left in you IE specific style sheet.


text:
Q: Ionic 4: 'Typescript error' in helperService Cannot read property 'length' of undefined at HelperService Getting error 'Cannot read property 'length' of undefined at HelperService.addCommasToArray' when trying to loop through an array that has been passed as a paramter in a helperService class [Typescript]
I'm really not sure why this is not working - I believe it should be straightforward - all I'm trying to do is pass in an array as a parameter and add a ',' to every value in the array (except the last value)
Here is my HelperService Class method:
 export class HelperService {

   constructor() { }

    /*
    * Add commas to every value in the array except for the last value
    */
     addCommasToArray(array: Array<any>) : Array<any> {

         for (let i = 0; array.length; i++){
              array[i] += ", ";
             }
         return array;
         }
 }

I then call this method within the ngInit of another ts class
  this.helperService.addCommasToArray(this.previousClubs);

Here is the ngInit method
  public previousClubs: Array<any>;

     constructor(private playersService: PlayersService,private
      helperService: HelperService, private route: ActivatedRoute) { }

 ngOnInit() {
     const playerId: string = this.route.snapshot.paramMap.get('id');
      this.playersService.getPlayerDetails(playerId).get()
      .then(playerDetailsSnapshot=> {
          this.currentPlayerDetails = playerDetailsSnapshot.data();
          this.currentPlayerDetails.id = playerDetailsSnapshot.id;
      });

     /*
      * Return Previous Clubs
      */
        this.playersService.getPreviousClubs(playerId).get().then(
 previousClubsSnapshot =>{
         this.previousClubs = [];
             previousClubsSnapshot.forEach(snap => {
                 this.previousClubs.push({
                     id: snap.id,
                     name: snap.data().name,
                 });
                 return false;
             });
         });

        this.helperService.addCommasToArray(this.previousClubs);
     }

A: so here:
this.playersService.getPreviousClubs(playerId).get().then(
 previousClubsSnapshot =>{
         this.previousClubs = [];
             previousClubsSnapshot.forEach(snap => {
                 this.previousClubs.push({
                     id: snap.id,
                     name: snap.data().name,
                 });
                 return false;
             });
         });
// this line executes without awaiting for .then enclosed scope
this.helperService.addCommasToArray(this.previousClubs);

Basically you call addCommasToArray even before your previousClubs var gets array assigned to it and then gets all its items pushed in. To fix since your method is (.then) async you need to call for this method inside the .then execution scope:
ngOnInit() {
     const playerId: string = this.route.snapshot.paramMap.get('id');
      this.playersService.getPlayerDetails(playerId).get()
      .then(playerDetailsSnapshot=> {
          this.currentPlayerDetails = playerDetailsSnapshot.data();
          this.currentPlayerDetails.id = playerDetailsSnapshot.id;
      });

     /*
      * Return Previous Clubs
      */
        this.playersService.getPreviousClubs(playerId).get().then(
 previousClubsSnapshot =>{
         this.previousClubs = [];
         previousClubsSnapshot.forEach(snap => {
                 this.previousClubs.push({
                     id: snap.id,
                     name: snap.data().name,
                 });
                 return false;
             });
         });
         this.helperService.addCommasToArray(this.previousClubs);
     }


text:
Q: like and dislike only once php JS mySQL I'm currently stumped on a problem. I'm trying to add like and dislike buttons for a displayed video, however, the user can only like it once and not multiple times. I'm getting the following errors,

Notice: Object of class mysqli_result could not be converted to int
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE v_id='34'' at line 1

<?php
session_start();
include "config.php";

if( !empty( $_GET['$v_id'] ) ){

    $vid = $_SESSION['v_id'] = $_GET['$v_id'];

$sql='SELECT video_name FROM video WHERE v_id=?';
    $stmt=$link->prepare( $sql );
    $stmt->bind_param('i', $vid );
    $res=$stmt->execute();
    if( $res ){
        $stmt->store_result();
        $stmt->bind_result( $videoname );
        $stmt->fetch();

        printf('
            <video width="70%%" height="70%%" style="background-color:#585858; border: 4px solid darkorange; border-radius:20px;" controls>
                <source src="uploads/%s" type="video/mp4" id="vid">
            </video>
        ', $videoname );
    }
} else {
    exit('missing ID');
}
$lk = mysqli_query($link, "SELECT likes FROM video WHERE v_id='$vid'");
$likeCount = 0;
$sumlk = ($lk + $likeCount);
$liked = mysqli_query($link, "INSERT INTO video(likes) VALUES('$sumlk') WHERE v_id='$vid'");
?>

<?php echo '$liked'; ?>

<?php
$func = <<<EOD

EOD;
?>

Below is the mySQL,
CREATE TABLE video(
v_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
video_name VARCHAR(225) NOT NULL,
id INT NOT NULL,
FOREIGN KEY user_id(id)
REFERENCES users(id)
ON DELETE CASCADE,
n_views INT,
likes INT,
dislikes INT,
image_name VARCHAR(225) NOT NILL
);

A: mysqli_query returns a result object. In this result object you can use methods like fetch_assoc() to get the actual rows and columns you're requesting.

A: if you want change  the value where  v_id  =  you_actula value
you should use an  update and not an insert
   UPDATE video
   set likes = '$sumlk'
   WHERE v_id='$vid'

any way you should not use php var in sql  you should use prepared statement and binding param as in your first select


text:
Q: Which version of widgetset Vaadin 7 application is using? Is there a way to determine the version of the widgetset downloaded?
I have an application that is a Vaadin application, I should want to find a command to launch in the console of chrome that tells me, which version of the widgetset is in use?