Bootstrap TagsInput with EntityType dropdown values (Symfony)

Question: I'm making a form to register books (Symfony 4), each with a unique publisher (ManyToOne) and one or many authors (ManyToMany). Both fields are filled in the form as tags, with Bootstrap TagsInput, so that if the user types in those fields, they will suggest the list of values in the DB tables, and if not, the new values will be inserted when submitting, along with the other book data.
I followed the official example of Best Practices on the Symfony website, and the tagging system works for authors, because it's a CollectionType, but not with the publisher, because it's an EntityType. How could I adapt it? Fails to transform publisher values into comma-separated strings so it can be recognized by TagsInput.
Book Entity (App\Entity\Book.php)
namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Book
{
    /**
    * @var \Publisher
    *
    * @ORM\ManyToOne(targetEntity="Publisher", cascade={"persist"})
    * @ORM\JoinColumns({
    *   @ORM\JoinColumn(nullable=false, name="publisher_id", referencedColumnName="id")
    * })
    */
    private $publisher;

    /**
     * @var Author[]|ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Author", cascade={"persist"})
     * @ORM\JoinTable(name="authors_books")
     */
    private $authors;

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

    public function getPublisher()
    {
        return $this->publisher;
    }

    public function getAuthors(): Collection
    {
        return $this->authors;
    }
}

Book Form (App\Form\BookType.php)
namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use App\Form\Type\PublisherType;
use App\Form\Type\AuthorType;

class BookType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder
        ->add('publisher', PublisherType::class, array(
            'label' => 'Publisher',
        ))
        ->add('authors', AuthorType::class, array(
            'label' => 'Author/s'
        ))
    }
}

AuthorType
namespace App\Form\Type;

use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer;
use App\Form\DataTransformer\AuthorToStringTransformer;
use App\Repository\AuthorRepository;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class AuthorType extends AbstractType {
    private $authors;

    public function __construct(AuthorRepository $authors_repo)
    {
       $this->authors = $authors_repo;
    }

    public function buildForm(FormBuilderInterface $builder, array $options){
       $builder
            ->addModelTransformer(new CollectionToArrayTransformer(), true)
            ->addModelTransformer(new AuthorToStringTransformer($this->authors), true)
        ;
    }

    public function buildView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['authors'] = $this->authors->findAll();
    }

    public function getParent()
    {
        return TextType::class;
    }
}

PublisherType
namespace App\Form\Type;

use App\Form\DataTransformer\EntityToArrayTransformer;
use App\Form\DataTransformer\PublisherToStringTransformer;
use App\Repository\PublisherRepository;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class PublisherType extends AbstractType {

    private $publishers;

    public function __construct(PublisherRepository $publisher_repo) {
        $this->publishers = $publisher_repo;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ->addModelTransformer(new EntityToArrayTransformer(), true)
        ->addModelTransformer(new PublisherToStringTransformer($this->publishers), true);
    }

    public function buildView(FormView $view, FormInterface $form, array $options): void
    {
        $publishers = $this->publishers->findAll();
    }

    public function getParent()
    {
        return TextType::class;
    }
}

CollectionToArrayTransformer
namespace Symfony\Bridge\Doctrine\Form\DataTransformer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\DataTransformerInterface;

class CollectionToArrayTransformer implements DataTransformerInterface
{
    public function transform($collection)
    {
        if (null === $collection) {
            return [];
        }
        if (\is_array($collection)) {
            return $collection;
        }
        return $collection->toArray();
    }
}

EnityToArrayTransformer
namespace App\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class EntityToArrayTransformer implements DataTransformerInterface
{
    public function transform($entity)
    {
        if (null === $entity) {
            return [];
        }
        return [$entity];
    }
}

AuthorToStringTransformer
namespace App\Form\DataTransformer;

use App\Entity\Author;
use App\Repository\AuthorRepository;
use Symfony\Component\Form\DataTransformerInterface;

class AuthorToStringTransformer implements DataTransformerInterface
{
    private $authors;

    public function __construct(AuthorRepository $authors)
    {
        $this->authors = $authors;
    }

    public function transform($authors): string
    {
        /* @var Author[] $authors */
        return implode(',', $authors);
    }

    public function reverseTransform($string): array
    {
    ...
    }
}

PublisherToStringTransformer
namespace App\Form\DataTransformer;

use App\Entity\Publisher;
use App\Repository\PublisherRepository;
use Symfony\Component\Form\DataTransformerInterface;

class PublisherToStringTransformer implements DataTransformerInterface
{
    private $publishers;

    public function __construct(PublisherRepository $publishers)
    {
       $this->publishers = $publishers;
    }

    public function transform($publisher): string
    {
        /* @var Publisher[] $publisher */
        return implode(',', $publisher);
    }

    public function reverseTransform($publisher): string
    {
    ...
   }
}

Form Twig
{{ form_widget(form.publisher, {'attr': {'class': class, 'data-toggle': 'tagsinput', 'data-publishers': form.publisher.vars.publishers|json_encode } }) }}
{{ form_widget(form.publisher, {'attr': {'class': class, 'data-toggle': 'tagsinput', 'data-authors': form.publisher.vars.authors|json_encode } }) }}

This is the code I use for Editors and Authors, so that you can compare the one that works and the one that doesn't work. They are not so different, but something is wrong, and I don't know what it is or what I need to change.
Answer: Ok, I've found a solution. I have made all the changes in both Transformers, because the problem was the format to which I converted the entity and vice versa.


Android-Starting new Activity in Handler/runnable is really slow

Question: I am making an android app that requires a runnable. I am starting a new activity from the runnable. The new activity comes up and works fine. The issue is that when the call is made to start the activity, it is incredibly slow. It takes a full 5 seconds to start the activity when I want it to be instantaneous.
<code>Boolean handlerrun=true;
Intent intent= new Intent(this,newactivity.class);
int somevalue=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
            setContentView(R.layout.gameactivity);

handler=new Handler();

final Runnable r = new Runnable()
{

    public void run()
    {
if(handlerrun){somevalue++;}

if(somevalue>500){
handlerrun=false;
startActivity(intent);
finish();
        }

        handler.postDelayed(this, 1);}

}
};

handler.postDelayed(r, 1);

}
</code>
The activity starts when somevalue is greater than 500. To stop the handler from increasing the value of somevalue, I use a boolean handlerrun, which only runs the handler when it is true. When somevalue is greater than 500, handlerrun= false so the handler doesn't increase the value. I tried using the handler.removeCallbacksandMessages() method but it didn't work. Logcat doesn't give me any errors.Any help would be appreciated.
Answer: You could try something like this:
<code>@Override
protected void onResume() {
    super.onResume();

    if(done){
        return;
    }
    done = true;
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            startActivity(new Intent(getApplicationContext(), YourActivity.class));
            finish();
            overridePendingTransition(0, 0);
        }
    }, 5000);
}
</code>
That will start YourActivity after 5 seconds approximately.
Hope it helps.


Error when running SonarQube on TFS build

Question: I have setup a SonarQube 5.2 server following the PDF document "SonarQube Setup Guide For .NET users".
The server starts and I can access the website. I added the C#, TFVC, and msbuild runner plugins.
The server hosting the sources is TFS2015 and I have existing build definitions in XAML. When I try to start a build I get the following exception:
<code>Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: tfsUri
at SonarQube.TeamBuild.Integration.CoverageReportUrlProvider.GetCodeCoverageReportUrls(String tfsUri, String buildUri, ILogger logger)
at SonarQube.TeamBuild.Integration.TfsLegacyCoverageReportProcessor.TryGetBinaryReportFile(AnalysisConfig config, TeamBuildSettings settings, ILogger logger, String& binaryFilePath)
at SonarQube.TeamBuild.Integration.CoverageReportProcessorBase.ProcessCoverageReports()
at SonarQube.TeamBuild.PostProcessor.CoverageReportProcessor.ProcessCoverageReports()
at SonarQube.TeamBuild.PostProcessor.MSBuildPostProcessor.Execute(String[] args, AnalysisConfig config, TeamBuildSettings settings, ILogger logger)
at SonarQube.TeamBuild.PostProcessor.Program.Main(String[] args)
Exception Message: TF270015: 'MSBuild.SonarQube.Runner.exe' returned an unexpected exit code. Expected '0'; actual '255'. See the build logs for more details. (type UnexpectedExitCodeException)
Exception Stack Trace:    at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
</code>
I have seen that I need to define the collectionUri property. I have done so on the server web page in the SCM category under General Settings.
Any idea why the value cannot be found ?
Any help would be very much appreciated.
Thanks,
Sergueï
Comment: Have you installed TFS 2015 Update 1? I think it's a requirement, though I can't remember where I read that
Answer: Turns out we are using multiple build agents in our environment and the one I used for this test was still running Team Foundation Server 2013. Updating it solves the issue.
I am sorry for the useless post.


How to draw a conditional distribution graph for B given A

Question: Below is a frequency table which has data for testing a theory that students who speak a foreign language are also strong mathematics students.
The question says to draw a graph showing conditional distribution of Math grade with the ability to speak a foreign language and give my conclusions. I computed the conditional distributions of Math grade for students who speak a foreign language and drew the below graph but it was marked incorrect.

I don not understand why this is incorrect. Do I need to draw a side-by side graph? Something like this?
Answer: Yes, otherwise in the first graph you have conditioned only on one level of the variable "Ability to speak ...".
In your second graph both levels are shown and you can see the relationship between the grades and the ability to speak a foreign language.
Comment: I've been discussing with a friend. I'm not sure whether I have computed the probabilities properly. Correct me if I'm wrong; the probability should be what percent of students speak foreign language per grade - among who got grade A (0.823 = 70/85) can speak a foreign language, and 0.176 (15/85) can not speak a foreign language?
Comment: Ok that's conditioning on the other variable. You had math conditioned on ability first - distribution of math grade conditioned to ability "does speak":
`P (A / speak) = 70/100;
P (B / speak) = 20/100;
P (C / speak) = 10/100`

but if you need *"percent of students speak foreign language per grade"* then use distribution of ability conditioned to math grade A:
`P (speak / A) = 70/85;
P (doesn't / A) = 15/85`


$H-\Lambda H \Lambda > 0$ if $H>0$ and $\mathbf{0}_n<\Lambda<\mathbf{1}_n$?

Question: Let $H>0$ be a $(n\times n)$-positive definite Hermitian matrix. Let $\mathbf{0}_n<\Lambda=\{\lambda_1,\ldots,\lambda_n\}<\mathbf{1}_n$ be a diagonal matrix with entries $0<\lambda_j<1\,(1\leq j \leq n)$. Then can we say that $H-\Lambda H \Lambda > 0$?
Answer: The answer in general is no and you can see this by tackling an easier problem and wielding continuity.
First I assume $H$ is not diagonal, and then fix some selection of $\mathbf{0}_n<\Lambda=\{\lambda_1,\lambda_2,\ldots,\lambda_n\}<\mathbf{1}_n$  now define
$\Lambda' :=\{1,\lambda_2,\ldots,\lambda_n\}$

technical nit:
if column 1 of $H$ is propotional to the 1st std basis vector, then instead 'attack' column $j$ which is not proportional to $\mathbf e_j$ and do this by instead selecting
$\Lambda' :=\{\lambda_1,\ldots,\lambda_{j-1},1,\lambda_{j+1},\ldots,\lambda_n\}$. Since $H$ is not diagonal, it is easiest to just assume WLOG that column 1 of $H$ has at least 2 non-zero components-- and the argument here tacitly does this.

Then
$\big(H-\Lambda' H \Lambda'\big)$
is a Hermitian matrix with a zero in the top left corner but that first column is non-zero, hence the matrix is not positive semi-definite.  (i.e. it necessarily has mixed signature).   Finally for $\tau \in [0,1]$ define
$\Lambda(\tau):= \tau \cdot \Lambda + (1-\tau)\cdot \Lambda '$
By topological continuity of eigenvalues
$\Big(H-\Lambda(\tau) H \Lambda(\tau)\Big)$ is not positive semi-definite for $\tau \in [0,\delta)$ for some $\delta \gt 0$. And setting e.g. $\tau:= \frac{\delta}{2}$ gives a counter-example.
Comment: It seems that you have different question now as your follow-up-- for Hermitian PD matrices $A$, $B$ where $A-B \succeq \mathbf 0$ can we say the ordered eigenvalues of $A$ (weakly) dominate those of $B$?  The answer is yes though it takes some work.  I gave a proof via Cauchy Interlacing here: https://math.stackexchange.com/questions/4246815/edit-a-question-on-eigenvalues-of-non-negative-matrices/4247059#4247059 .
Comment: Thank you for the nice explanation. I was wondering however, that can we say something about the bounds on eigenvalues of $\Lambda H \Lambda$ here? Suppose we start from $\Lambda^2<\mathbf{1}_n$. Then $H^{1/2}\Lambda^2 H^{1/2}<H$. Now as eigenvalues of $H^{1/2}\Lambda^2 H^{1/2}=(H^{1/2}\Lambda)(\Lambda H^{1/2})$ are the same as those of $(\Lambda H^{1/2})(H^{1/2}\Lambda)=\Lambda H \Lambda$, can we say that the ordered eigenvalues of $\Lambda H \Lambda$ are less than the ordered eigenvalues of $H$?


How do I turn on specialization to eliminate runtime dictionary passing?

Question: While looking at poor runtime performance of some Purescript code I wrote, I noticed that the generated Javascript code contains dictionary passing for overloaded definitions for e.g. transformers monads. However, all my exported functions are monomorphic, so the compiler should have no trouble specializing these overloaded occurrences.
If this were Haskell compiled with GHC, I'd check optimization flags, and things like making sure nothing is marked NOINLINE and that unfoldings are properly exposed for specialisable definitions. What are the equivalent techniques for Purescript?
Answer: PureScript v0.15.3 has an optimization for "common subexpression elimination for expressions created by the compiler in the process of creating and using
typeclass dictionaries." Maybe that will speed up your code.
Comment: I can't really observe any effect of this. I have one module that is still compiled into a `.js` file where dictionaries are passed around, and the `.js` file resutling from my other, main module, still doesn't contain any specialised versions of these functions.
Comment: If you have a case where you think you should be seeing the optimization but you're not, then I'm sure the PureScript project would like you to open an issue and describe what you're seeing.


Como utilizar oninvalid no textarea [HTML5]

Question: Queria saber como utilizar o oninvalid no text area.
 <textarea type="text" pattern=".{1,255}" id="mensagem" name="mensagem" class="form-control no-resize" rows="6" placeholder="A mensagem" required maxlength="255" autofocus
     oninvalid="setCustomValidity(this.validity.patternMismatch ? 'Quantidade de caracteres excedida.' : '')"></textarea>

Pois desta forma nao esta funcionando!
Answer: Caro,
Para que o elemento <textarea> seja inválido é necessário submeter o campo dentro de um elemento <form>, no entanto, em sua validação apenas o atribute required irá validar o textarea. No HTML5 o atributo pattern não está disponível para o elemento <textarea>, neste caso terá que validar o length na mão.
Exemplo para executar a validação:

    <form>
      <textarea required oninvalid="alert('é obrigatório');"></textarea>
      <button>submit</button>
    </form>

Referência
Abraço.


exclude specific folder from library

Question: I have a library that is incompatible with java8. It's xws-security:3.0. I can't use it fully because there's trouble in crypto/xmldsig/1.0.
On the screenshot, you can see situation in the intellij idea.
How can I solve this problem by gradle exclude?

Answer: You can download it from repository and then install it into your local repo. https://springframework.svn.sourceforge.net/svnroot/springframework/repos/repo-ext/javax/xml/crypto/xmldsig/1.0/xmldsig-1.0.jar
Code:
mvn install:install-file -Dfile=xmldsig-1.0.jar -DgroupId=javax.xml.crypto -DartifactId=xmldsig -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true -DcreateChecksum=true

exclude specific folder from library


How to test if a service is called from the component in angular

Question: I have a component which on init calls getAllUsers() method and getAllUsers() calls getAllUsersApi from my service. I want to test if both the calls are actually made.
Here are some snippets from my code:
test.component.ts
ngOnInit(){
  this.getAllUsers();
}
getAllUsers(){
   this.userService.getAllUsersApi('');
}

test.service.ts
getAllUsersApi(){
   return this.http.get('api/endpoint')
}

test.service.spec.ts
it('should call getAllUsers method on init'){
  spyOn(userService, 'getAllUsersApi');
  spyOn(component, 'getAllUsers');
  component.ngOnInit();
  expect(component.getAllUsers).toHaveBeenCalled();
  expect(userService.getAllUsersApi).toHaveBeenCalled(); // it fails here
}

But it fails here: expect(userService.getAllUsersApi).toHaveBeenCalled();
Can anyone please help me what I am doing wrong.
Answer: The reason your test fails, is because your component spy componentSpy is actually replacing your getAllUsers function in your component with an empty stub and therefore your getAllUsersApi call will never happen. and.callThrough will set up a spy and make sure the original function is being called.
I would test it like this:
it('should call getAllUsers method on init', () => {
  // set up spies, could also call a fake method in case you don't want the API call to go through
  const userServiceSpy = spyOn(userService, 'getAllUsersApi').and.callThrough();
  const componentSpy = spyOn(component, 'getAllUsers').and.callThrough();

  // make sure they haven't been called yet
  expect(userServiceSpy).not.toHaveBeenCalled();
  expect(componentSpy).not.toHaveBeenCalled();

  // depending on how your component is set up, fixture.detectChanges() might be enough
  component.ngOnInit();

  expect(userServiceSpy).toHaveBeenCalledTimes(1);
  expect(componentSpy).toHaveBeenCalledTimes(1);
});

Comment: Thanks Fabian. It helped.


Class não encontrada no servidor remoto

Question: Tenho o seguinte arquivo index.php
<?php

  require_once 'global/erros/erros.ini';
  require_once 'vendor/autoload.php';

  use CLASSES\INIT\Init;

  new Init();

?>

E a seguinte classe Init.php
<?php

  namespace CLASSES\INIT;

  use CLASSES\CONFIG\Config;

  class Init extends Config {

    protected function iniciaRotas() {

        $ar["home"]     = array("rota"=>"/crud/", "controle"=>"site", "acao"=>"index");
        $ar["index"]    = array("rota"=>"/crud/index", "controle"=>"site", "acao"=>"index");
        $ar["admin"]    = array("rota"=>"/crud/admin", "controle"=>"admin", "acao"=>"index");

        $this->configRotas($ar);

   }

  }
?>

E o seguinte autoload_ps4
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'CLASSES\\' => array($baseDir . '/classes'),
);

Então, localmente (localhost) funciona.
Mas quando subo para o servidor dá erro:
Fatal error: Class 'CLASSES\INIT\Init' not found in
/var/www/html/funerariasaopedro.net.br/web/crud/index.php on line 8

Não faz muito sentido!
Árvore
\
\index.php
\classes\
\classes\init\
\classes\init\Init.php

Como eu parei no composer.json para gerar o autoload_psr4.php?
Desta forma:
'CLASSES\\UTIL\\'  : '/classes/util',
'CLASSES\\MVC\\CONTROLES\\'  : '/classes/mvc/controles'

Ou dessa?
'CLASSES\\UTIL\\Util\\'  : '/classes/util/Util.php',
'CLASSES\\MVC\\CONTROLES\\Administradores\\'  : '/classes/mvc/controles/Administradores.php',
'CLASSES\\MVC\\CONTROLES\\Base\\'  : '/classes/mvc/controles/Base.php'

Answer: Localmente deve estar a funcionar porque o Windows, normalmente, é case-insensitive.
No servidor, que deve ser baseado em linux, será case-sensitive.
Podes mudar o vendor/autoload.php para converter o caminho sempre para lowercase, se, for sempre essa a tua regra, ou então mudar no use CLASSES\INIT\Init; para representar o que está no filesystem, mas ai provavelmente vais ter de mudar em vários ficheiros.
Tem também atenção que o autoload.php que estás a usar foi gerado pelo composer alterar esse ficheiro pode ter outras consequências.
Comment: pois é. Mas como podes ver na pegunta, os caminhos e os nomes dos arquivos estão corretamente definidos respeitando case-sensitive regra!
Comment: Não sei, tenho quase a certeza que é esse o problema, porque o erro diz `Fatal error: Class 'CLASSES\INIT\Init' not found in` mostrando que está a tentar aceder a uma pasta `CLASSES\INIT`, tal como tens no `uses`, e na lista de pastas que mostras no exemplo `Árvore` eles estão com lowercase. O código também não indica haver outro problema, até porque funciona no teu local, e assumo que todos os ficheiros estejam no servidor.
Comment: CLASSES\INIT\Init não é pasta. É namespace!
Comment: Certo! Mas o autoload usa isso pra saber onde ir buscar o ficheiro que indicas ai
Comment: Os namespaces tem que ser exatamente os nomes das pastas? É isso? Se for, realmente está errado. Mas peguei exemplo na internet
Comment: Não tem mesmo de ser o caminho tal como está no filesystem, mas por norma é. A função de `autoload` é que usa o caminho especificado no `uses` para perceber onde ir procurar o ficheiro indicado e automaticamente o carregar, sem teres de usar `include` ou `require`, ele faz isso por ti.
Comment: adicionei dados ao final da pergunta. dá uma olhada fazendo favor?

Class não encontrada no servidor remoto


Show $x^{\alpha }$ is well defined.

Question: I'm trying to show that the function  $f_n :[0,\infty )\rightarrow [0,\infty ) $ given by $x\mapsto x^n$ satisfies the property $x^{\alpha + \alpha ' }=x^{\alpha } x^{\alpha ' } , \alpha , \alpha ' \in \mathbb{Q} .$
I'm supposed to use that $x\mapsto x^{nn'} $ is injective but I'm unsure on how to show this.
Answer: Are you asking why $x^{\alpha+\alpha'}= x^\alpha x^{\alpha'}$ for any pair of rational points $\alpha = \frac{a}{b}, \alpha' = \frac{a'}{b'}$? If this is what you mean, try showing that $(x^{\alpha + \alpha'})^{bb'} = \left ((x^\alpha)(x^{\alpha'})\right)^{bb'}$. Injectivity of the map $t \mapsto t^{bb'}$ will then give you the desired equality $x^{\alpha+\alpha'}= x^\alpha x^{\alpha'}$.
Comment: For RHS I get $x^{a'b}.x^{ab'} $ and for LHS I get $ x^{a'b+ab'} $ but I don't get how I can prove that these are equal.
Comment: $a'b$ and $ab'$ are both integers. It is a consequence of definition that $x^{p + q} = x^px^q$ whenever $p,q$ are integers.

Show $x^{\alpha }$ is well defined.


how to derive relation between solid angle and surface area and the radius of sphere using definite integral?

Question: how to derive relation between solid angle and surface area and the radius of sphere ?
I know $s=r^2\Omega$    but how they got it using integral ?
Comment: How do you define solid angle if not by this?  The factor $r^2$ is needed to make the dimensions consistent.
Comment: @RossMillikan for example I can find in a circle that $l=r \theta $ using integral but here in my problem I dont know how
Comment: You can do similar, using a small patch of the sphere as a differential of area and integrating.  You use the known formula for the volume of a pyramid like you use the area of a triangle in the 2D case
Comment: @RossMillikan can you add your way to an answer with more explain ?
Comment: Do you already know the volume of a sphere is $\frac 43 \pi r^3$?  These are related
Comment: @RossMillikan yes
Answer: One way is to start from the volume of a unit sphere.  Using the disk method, it is $\int_{-1}^1 \pi (1-z^2)dz=\pi(z-\frac{z^3}3)|_{-1}^1=\frac 43\pi$  The volume of a sphere of radius $r$ is then $\frac 43 \pi r^3$.  The surface area is then the derivative of this with respect to $r$-think of increasing $r$ a small amount $dr$ and the volume added.  This gives the total solid angle is $\frac d{dr} \frac 43 \pi r^3=4\pi r^2$
Comment: but how to prove that surface area is the derivative of the volume with respect to r ?
Comment: If we put a shell around the sphere of thickness $dr$, the volume is $dr$ times the area of the sphere.
Comment: mmmmm , can you explain more please ? and its better for me when you using another way :)
Comment: Maybe think of expanding a cube the same way.  If you have a cube of side $a$, the volume is $a^3$.  If you expand the side to $a+2da)$ (where I added the factor $2$ because the side of the cube is like the diameter of a sphere) the volume becomes $a^3+3 a^2(2da) + 3a(2da)^2+(2da)^3$  Each term  of this can be identified with pieces of the larger cube.  The $a^3$ is the original cube, the next are the extensions of the faces, the next are long skinny pieces along the edges, and the final is the corners.  All but the faces are another order smaller and can be ignored.


Can $x$ be written as a $\mathbb{Q}[x,y]$-algebraic combination of $x+xy$, $y+xy$, $x^2$, and $y^2$?

Question: I was wondering how to write $x$ as an algebraic combination of $\{x+xy,y+xy,x^2,y^2\}$, with the coefficients $\in \mathbb Q[x,y]$.
Comment: I think that the kind of combination that you want is called an _algebraic_ combination.
Comment: I've revised my answer to include a solution to this new, edited problem. See my post below.
Comment: @alex.jordan Thanks.
Answer: New problem: Take $(x+xy)-x(y+xy)+y(x^2)$. This simplifies to $x+xy-xy-x^2y+x^2y=x$.
Old problem: This is not possible. To see why, examine $x= a(x+xy)+b(y+xy)+cx^2+dy^2$ with $a,b,c,d\in\mathbb{Q}$. We then have that $x= ax+by+(a+b)xy+cx^2+dy^2$. Equating coefficients, we see that $b$ must be 0 and $a$ must be 1. But then the coefficient of $xy$ is 1 on the RHS and 0 on the LHS, which is a contradiction.
Comment: Cool! Thanks a lot.


Basics in Complex Analysis

Question: I am learning complex analysis and having doubts in the basics as follows:-

I read that the derivative of a complex valued function $f(z)$
behaves exactly in the similar fashion as if it were a real valued
function $f(x)$.I would like to know why that happens. If i guess
that it is because the definition of differentiability in both the
worlds, the complex as well as the real is $'identically'$ similar .
If there's more to it ,please help me here.
The integral of a complex-valued function is defined along a contour as the sum of the product of the function value at $z$ times the displacement $dz$ .What does this represent if it's not area under the curve ? $$\int_\gamma f(z)\,dz .$$
Following from above ,in complex integrations , we essentially multiply two complex numbers (i.e. $f(z)$ and $dz$) , simplify them to a single number and then integrate. How is this action inside an integral is justifiable ?
In Cauchy's theorem of analytic functions in a simple closed curve , is it necessary to have
function $f(z)$ being $'extending ...smoothly'$ towards the contour. Is it necessary as well as suffficient if the function is only analytic on and inside the contour and outside the contour it can behave in a rather funny way.Can that happen ?

If there's some text that people here can share on complex analysis , that would be really helpful.
Thanks for helping.
Comment: For #2: while area under a curve was a big motivation for defining (real-valued) integrals, the actual definition is a limit of Riemann sums. We then find that limits of Riemann sums come up in other contexts as well (such as finding volumes of solids of revolution), which reinforces the fact that integrals are really limits of Riemann sums, more fundamentally than they are areas. Contour integrals are simply limits of Riemann sums where the summands can be complex (which is also the answer to #3).
Comment: the definition of the integral in the complex plane is namely $\int_{c} f(z)dz=\int_{a}^{b} f(z(t))z'(t)dt$, where $c$ parametrized by $z(t)=x(t)+iy(t)$, in my understanding this definition is special in the sense that we have cauchy theorems analogous to line integrals of vector fields
Comment: if however you expand $f$ as $f=u+iv$, in the integral definition, you get $\int_{c} f(z)dz=\int_{c}[u,-v]+i\int_{c}[v,u]$ so that the integral definition can be intuitively thought as the line integrals of the vector fields $[u,-v], [v,u]$ on the contour c
Comment: as for the motivation,  it is very clear that analytic functions satisfy a number of very fundamental properties and by using this definition the expression of such properties becomes very simple, as you can see from cauchy integral formula, or that functions that are holomorphic on a domain d are infinitely differentiable, such strong statement is derived from this definition.
Comment: @GregMartin Sir, meaning the integrals came into picture as a special symbol just to evaluate limit of reimann sums and then we found out that they , in real world, gives area under the curve .this is quite remarkable .
Comment: @muhammad how about the fourth point . this term 'extending...smoothly' just outside the domain D of where an analytic function is defined in cauchy's theorem ?
Comment: as far as i know, the definition of the contour is that it is a "smooth arc" meaning that the derivative of the parametrization of such contour doesnt vanish, e.g $z'(t)\neq 0$, on the other hand cauchy theorem only demands that $f$ be analytic inside and on the contour c, it is irrelevant what happens outside the contour. as for contour itself, you can show that cauchy theorem still holds even if the curve intersects an infinite number of times
Answer: Is this one question or four questions?
(1). The derivative of a complex function is not at all (other than superficially) like that of a real function.  For example, if a complex function has one derivative, it has infinitely many derivatives!
(2). A contour integral could represent various physical entities (for example work) depending on the context.  Green's theorem and Stokes' theorem relate a contour integral to an "area" or "volume" integral.  In any case, the integral needs no physical analogue.
(3).  The term $dz$ is a differential, similar to the role of differential in a real integral.
(4).  In Cauchy's theorem, $f(z)$ is holomorphic (it has a derivative).
Please read "Chapter zero" of Stein and Shakarchi, Complex Analysis for more motivation.
Comment: I am sorry. Thanks for mentioning the book.
Comment: No need to apologize.  You are welcome.
Answer: I think the source of the problem is thinking about the integral primarily as "the area under a curve".  That's one application of integration, but it isn't what integration is.  Integration is the infinite sum of infinitely small values.  That's why complex integration works just like real integration.  $f(z)\,dz$ is just an infinitely small value that gets summed.  It works for multivariable equations just like single-variable equations.  It is literally just an infinite sum of infinitely small values.
The reason why, in the reals, it represents an area under a curve, is that if you divide the curve $f(x)$ into infinitely small rectangles, each rectangle will be $f(x)$ tall and $dx$ wide.  So, $\int f(x)\,dx$ is just the sum of all those areas.  But the function that the integration itself is performing is not area, but summation.  It doesn't matter to the integral that $f(x)\,dx$ represents an area or anything else.  Therefore, since addition works the same in the complex numbers as it does in the reals, integration also works the same, because it is just a summation.
If you realize that integration is just the infinite sum of infinitely small values, then I think that answers all of your questions, at least implicitly.
Comment: Sir , can you please share your insight on the fourth point.
Comment: 'If you realize that integration is just the infinite sum of infinitely small values'  - can we say that this is derived from integration being essentially limit of reimann sums ?

Basics in Complex Analysis


Formatting currency in Drupal Commerce

Question: I am using Views and Drupal Commerce in Drupal 7 to display a list catalogue of products (books).
By default the price column is formatted "12.34 ZAR" which is a format that is only really used in an international currency trade context for South African Rand. How do I override the format so that I can display it as "R12.34" which is the more common format.
Answer: You can do it just for your site using hook_commerce_currency_info_alter(), but more appropriately check out the information in the Drupal Commerce FAQ on Currency Formatting to get the proper format in core. The reason it's showing up as 12.34 ZAR is because that's just the bland default format we use for currencies we didn't know how to format. : )
Comment: It's been quite a day. I've installed Git, set up a github account, created a cert, connected to the drupal repository, downloaded the latest version of commerce, downloaded the patch, applied it, and finally updated my site. Where it is working like a charm. Let's just say that the only step of this process that I knew what to do when I started was the 'updated my site' one' :-)
Comment: Thanks, Ryan. Logged the request in the [issue queue](http://drupal.org/node/1168114) My first ever Issue Log, whoa :-)
Comment: w00t - I just committed the patch from Haza. It'll be in the next release - welcome to contributor-hood. ^_^
Answer: You can use the Commerce Currency Settings module.  This will allow formatting to be configured from the Web UI.
Answer: Commerce Currency Settings module changes the Currency format sitewide.  I recommend using the:

Price formatter: Raw amount, exclude it from display
Global: Math expression, e.g. [commerce_price]/100 (Drupal commerce often uses the minor unit: pennies etc.)
Global: Custom text, e.g. R[expression]

This will allow you to use Views to display as you wish in the View without additional coding or modules.
This method can also be used for schema.org price itemprop, which requires decimal syntax without symbol, see: https://schema.org/price

Formatting currency in Drupal Commerce


Displaying bound list of svg files

Question: In my WPF application I have a grid with a fixed set of SVG Images (I use SharpVectors library)
<Image Grid.Column="0" Grid.Row="0" Source="{svgc:SvgImage Source=Resources/0.svg}" Stretch="Fill"/>
<Image Grid.Column="1" Grid.Row="0" Source="{svgc:SvgImage Source=/Resources/1.svg}" Stretch="Fill"/>
<Image Grid.Column="2" Grid.Row="0" Source="{svgc:SvgImage Source=Resources/2.svg}" Stretch="Fill"/>
<Image Grid.Column="1" Grid.Row="0" Source="{svgc:SvgImage Source=/Resources/3.svg}" Stretch="Fill"/>

Now I want to have item control where I would bind a list of paths to the SVGs, something like this:
<ItemsControl DataContext="{Binding DataContext}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Stretch="Fill" Width="100" Height="100">
                <Image.Source>
                    <renderers:SvgImageSource/>
                </Image.Source>
            </Image>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

But I don't get it how to use string path in the renderers:SvgImageSource tag.
Comment: What is SvgImageSource? SharpVectors only seems to have a SvgImageExtension class, which is a MarkupExtension.
Comment: As a note, `DataContext="{Binding DataContext}"` is entirely redundant.
Comment: @Clemens yeah, thanks, removed it
Answer: Set an ItemsSource for your SVG image URIs. Then you can use the SvgImageConverter for binding.
<ItemsControl ItemsSource="{Binding YourSvgUriItems}">
   <ItemsControl.Resources>
      <svgc:SvgImageConverter x:Key="SvgImageConverter"/>
   </ItemsControl.Resources>
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <Image Stretch="Fill" Width="100" Height="100"
                Source="{Binding Converter={StaticResource SvgImageConverter}}"/>
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

Answer: You could try to bind to the path and use the SvgImageConverterExtension class:
<Image Stretch="Fill" Width="100" Height="100">
    <Image.Source>
        <Binding Path="YourUriProperty">
            <Binding.Converter>
                <converters:SvgImageConverterExtension />
            </Binding.Converter>
        </Binding>
    </Image.Source>
</Image>

Displaying bound list of svg files


What's the target in my data for training a stock price predictor?

Question: I want to build a stock price predictor for an economical indicator in Venezuela, I've cleaned and structured the historical data that I want to use (from the last 10 years), but I have doubts because it's my first machine learning project, my CSV data with 3000+ entries looks like this:
2553
11-28-2017;0.8823561
2554
11-29-2017;0.9679446
2555
11-30-2017;0.9719271
2556
12-1-2017;1.0302427

As you can see column 0 have the date and column 1 have the price for that particular date, in this case the training data (X) should be the price, however the methods that I want to use expect both X and Y (supervised learning), since it's my first time obtaining my own data I feel a bit lost, there you have my code so far: https://github.com/marcelodiaz558/Venezuela-dollar-price-predictor/blob/development/model.ipynb I would like to train my model in the future with a LSTM or maybe I'll start with a simple Artificial Neural Network for testing, when I solve my doubts about the data, I don't know who Y should be.
Answer: Y / your target is what you want to predict. X / your training data is some vector representation of your prior knowledge that can be used to better your predictions of the unknown quantity. In a simple time-series prediction with a simple regressor, your training data could be the prices from the past N days.
So using your example data where you want to be able to predict the price one day in the future based on the prices from the last two days (N=2), your X and Y would be
X = [[0.8823561, 0.9679446], [0.9679446, 0.9719271]]
Y = [0.9719271, 1.0302427]

So to do machine learning on your data you would need to pre-process your data depending on exactly what you want. Some algorithms are specifically designed for this task, so will either not need pre-processing or it is done automatically in the implementation.
Answer: Unfortunately you picked a difficult problem to start with ML: Time Series
The issue here is that you has to respect the order of your values.
So a timeseries has:
Timestamp t-3: 0.8823561
Timestamp t-2: 0.9679446
Timestamp t-1: 0.9719271
Timestamp t(prediction/ y): 1.0302427

A really nice package comes with R which is called: ARIMA.
A problem is that you have to check if you have seasonal data (some patterns which regular occur in your data), stationary data (if the data trends to be stationary).
My recommendation, if you only want to start machine learning go for a classification problem with the iris dataset.


Censored Regression with different limits for some observations

Question: I'm attempting to model some data using regression analysis that has different upper limits for different observations, i.e. there is no universal limit for the entire data set. However I do have observations that have been censored, but the amount of censoring will sometimes change between observations? As I understand it the censReg R package accepts one universal upper limit, is there another option either within this package or in another package/language that would allow me to model observations with different upper limits?
If there is no other option then would using a similar approach to zero-inflated models accurately model this behavior? And by that I mean build a model to estimate when an observation might be censored and include that in the final distribution of what I am trying to predict. That's the only approach I can think of that might help with this distribution behavior.
Answer: Yes, censReg only supports a scalar censoring point, i.e., constant over observations.
As an alternative you may use the crch package whose crch() function supports left and right limits that may be varying over observations. Additionally, it optionally allows to model heteroscedasticity conditional on regressors.
Furthermore, the survival package's survreg() function also supports arbitrary censoring patterns which have to be set up through a suitable Surv() object. It provides more response distributions than the two aforementioned packages.


Print variable views template

Question: I have created a view with table format but i am not able to print field variables in twig template of view suppose machine name of eck field is field_large,field_quote_source and so on.

  {% for row in rows %}

  {% for key, column in row.columns %}
        {% for content in column.content %}
          {{- content.separator }}{{ content.field_output -}}
          {{ content.field_large }}
        {% endfor %}
  {% endfor %}

 {% endfor %}

Answer: This is the path for accessing single fields in a view table template, for example in the first row:
rows.0.columns.fieldname.content.0.field_output

In your code example, to get all field names available, use this in the first loop:
{{ dump(row.columns|keys) }}

The naming of the fields depends on how you have configured the view and is not necessarily the machine name of the field in the entity.
Comment: This line is only to show where you can find the field names. If you really want to work on this view template use xdebug, why and how to use xdebug is described in the official documentation https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates
Comment: Thank you so much ,but what is the logic behind this ,our drupal 8 concept is not so clear ,can you suggest me some tutorial links
Comment: Can you put the above line of code into loop ,again i am stucked

Print variable views template


non-interactive ssh session does not terminate, sshd process waits forever after a script exits

Question: We run a simple deployment script remotely using a command like ssh email@example.com sudo /root/run-chef-client.sh. It started to hang today because sshd waited forever on the 10.170.4.11 even after sudo had finished already. We started sshd in debug mode and got two different kind of logs. The following is a normal log when the session does not hang:
debug1: Received SIGCHLD.
debug1: session_by_pid: pid 23187
debug1: session_exit_message: session 0 channel 0 pid 23187
debug1: session_exit_message: release channel 0
Received disconnect from 10.170.4.6: 11: disconnected by user

And when it hangs we get the following:
debug1: Received SIGCHLD.
debug1: session_by_pid: pid 24209
debug1: session_exit_message: session 0 channel 0 pid 24209
debug1: session_exit_message: release channel 0

Our understanding is that the server process waits for some communication from a client side and never gets it. It's hard to tell if it is a client side or a server side problem.
We tried to run sshd under strace but did not succeed because a SUID bit on sudo was ignored it this case. So, what else should we try to debug/prevent this situations?
Answer: Using ssh -t (forced PTY allocation) on a client side solved the problem:
debug1: Received SIGCHLD.
debug1: session_by_pid: pid 31701
debug1: session_exit_message: session 0 channel 0 pid 31701
debug1: session_exit_message: release channel 0
debug1: session_pty_cleanup: session 0 release /dev/pts/1
Received disconnect from 127.0.0.1: 11: disconnected by user
debug1: do_cleanup
debug1: PAM: cleanup
debug1: PAM: closing session
debug1: PAM: deleting credentials

sshd is controlled by a pseudo TTY not by a client anymore.


Pegar as informações do formulário e envia-las para e-mail

Question: Possuo um formulário que terei que pegar as informações digitadas e enviar para o meu e-mail via java script ou jquery porem não sei como fazer isso até o momento somente validei o meu formulário segue o código do meu formulário:

.corpo-1 ul li {

  display: block;

  margin: 10px;

  text-align: center;

}

.corpo-1 ul {

  margin-top: 10%;

}

.contato-barra {

  width: 10%;

  height: 2px;

  background-color: #000;

  border: none;

}

input[type="text"] {

  border: 1px solid #000;

  border-radius: 5px;

  width: 300px;

  height: 25px;

  background-color: transparent;

  font-family: Gabriola;

  font-size: 1.2em;

  outline: none;

}

.teste1 {

  margin-left: 65%;

  background-color: aquamarine;

  width: 100px;

  height: 50px;

  color: #000;

  display: none;

}

select {

  border: 1px solid #000;

  border-radius: 5px;

  width: 300px;

  height: 40px;

  background-color: transparent;

  font-family: Gabriola;

  font-size: 1.2em;

  outline: none;

}

textarea {

  border: 1px solid #000;

  border-radius: 5px;

  width: 300px;

  height: 100px;

  background-color: transparent;

  font-family: Gabriola;

  font-size: 1.2em;

  outline: none;

}

#enviar {

  background-color: #000;

  width: 300px;

  height: 50px;

  border: none;

  border-radius: 5px;

  color: #fff;

  font-family: Gabriola;

  font-size: 1.3em;

  text-align: center;

  cursor: pointer;

  outline: none;

}

#enviar:hover {

  background-color: #333;

}

#bg-fundo {

  position: absolute;

  z-index: -1;

  opacity: 0.25;

  left: 0;

  right: 0;

  margin: auto;

  margin-top: -18%;

  /*width: 50%;*/

  transform: scale(1);

}

    <form method="post" action="">

          <input type="text" id="nome" placeholder="  Digite seu nome" required name=nome>

          <input type="text" placeholder="  Digite seu Email" required name=email>

          <input type="text" placeholder="  Digite seu Nickname" required name=nickname>

          <select>
            <option value="the-elder" selected>--- Selecione um jogo ---</option>
            <option value="the-elder">The Elder Scrols Online</option>
            <option value="archage">ArcheAge</option>
            <option value="worlofwarcraft">World of War Craft</option>
            <option value="forsaken">Forsaken World</option>
            <option value="leagueoflegends">League of Legends</option>
            <option value="dota">Dota 2</option>
            <option value="smite">Smite</option>
            <option value="warface">Warface</option>
            <option value="cs">CS-GO</option>
            <option value="bf">Battle Field</option>
            <option value="cod">Call of Dutty</option>
          </select>

          <textarea placeholder="  Mensagem" required name=mensagem></textarea>

          <input type=submit value="Enviar" id="enviar" />

    </form>

Obs: O meu email sera enviado para o meu no caso email@example.com
Answer: Não é possível enviar email usando somente JavaScript. Você deverá usar uma linguagem de servidor para isso, por exemplo PHP.
Mas você pode usar o comando window.open('mailto:email@example.com'); para abrir o programa de email padrão e enviar o email.
Você pode também passar parâmetros no comando: window.open('mailto:email@example.com?subject=assunto&body=corpo');
Exemplo em PHP:
<?php
$para       = 'firstname.lastname@example.com';
$assunto    = 'Algum Assunto';
$mensagem   = 'Olá';
$cabecalhos = 'From: email@example.com' . "\r\n" .
    'Reply-To: firstname.lastname@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($para, $assunto, $mensagem, $cabecalhos);
?>

Comment: @Kirito http://lmgtfy.com/?q=mailto
Comment: @Kirito Sobre como mandar email com PHP podes ver o manual oficial: http://php.net/manual/pt_BR/function.mail.php
Comment: @Kirito Atualizei a resposta com um exemplo em PHP.
Comment: existe alguma documentação disso ou algum lugar com o codigo pronto ou com mais informaçoes eu nao manjo dessas coisas
Comment: amigosei que nao e da sua conta mais sou muito ruim com essas linguagem seria possivel posar um prototipo de  codigo para eu poder entender melhor se nao for pedir muito
Comment: @Earendul amigo entao omeu arquivo contato esta com a extensão .html eu terei que mudala tbm e colocar .php??? e quanto a seu codigo eu coloco ele no corpo do meu site ou no head do meu arquivo
Comment: @Earendul   amigo abri um novo topico com meu codigo php da uma olhada la :  http://pt.stackoverflow.com/questions/66243/formul%C3%A1rio-n%C3%A3o-envia-as-informa%C3%A7%C3%B5es-para-o-e-mail
Answer: Realmente tem que usar uma linguagem no servidor para enviar seu e-mail. O PHP é muito bom nisso, leia aqui um artigo bem completo sobre como fazer isso.
Existe também o PHPMailer, aqui existe outro artigo explicando sobre ele.


Option>> dereferencing problem

Question: I'm new to Rust and facing problem trying to browse dynamic tree. In the example below I want to traverse all the nodes, starting from the given one and check for specific value.
use std::{cell::RefCell, rc::Rc};

pub struct TreeNode {
    pub value: i32,
    pub parent: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {

    pub fn check(&self, val: i32) -> bool {
        let mut curr = &self.parent;
        while let Some(p) = curr {
            if val == p.borrow().value {
                return true;
            }
            curr = &p.borrow().parent;
        }
        return false;
    }
}

pub fn main () {
    let node1 = TreeNode {
        value: 1,
        parent: None
    };
    let boxed_node1 = Rc::new(RefCell::new(node1));

    let node2 = TreeNode {
        value: 2,
        parent: Some(boxed_node1.clone())
    };
    let boxed_node2 = Rc::new(RefCell::new(node2));

    let result = boxed_node2.borrow().check(42);
    println!("result = {result}");
}

The compiler gives an error:
error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:16:21
   |
12 |         while let Some(p) = curr {
   |                             ---- borrow later used here
...
16 |             curr = &p.borrow().parent;
   |                     ^^^^^^^^^^       - temporary value is freed at the end of this statement
   |                     |
   |                     creates a temporary value which is freed while still in use
   |
   = note: consider using a `let` binding to create a longer lived value

Please help me to fix the check() function
Answer: Instead of curr holding a reference, you can clone the Rc and hold that instead. Here, I've done that while the Rc is still inside the Option. Since self isn't inside Rc, I've handled the first iteration separately.
pub fn check(&self, val: i32) -> bool {
    if val == self.value {
        return true;
    }

    let mut curr = self.parent.clone();
    while let Some(p) = curr {
        if val == p.borrow().value {
            return true;
        }
        curr = p.borrow().parent.clone();
    }

    false
}

Option>> dereferencing problem


Quem é quem no uso de funções?

Question: Tenho procurado muito, e tem muito conteúdo bom aqui, que abrange esse tema, entretanto ainda não consegui entender o funcionamento.
Os personagens a que me refiro são:

Funções
Parâmetros
Argumentos
Valores
Variáveis
Escopo

A resposta que tenho procurado, é um exemplo de um código com 2 ou mais funções, de forma que ficasse explícito o relacionamento e a necessidade desse relacionamento entre os personagens.
Vou tentar produzir um código que reflita minha dúvida.
Exemplo
retirado dessa resposta
class Teste {
    int x = 5; //escopo da classe, tempo de vida de acordo com a instância
    StringBuilder txt; //o mesmo
    int Metodo(int y) { //parâmetro existe dentro da função escopo/lifetime
        var x = 2; //note que há ambiguidade com a variável da classe
        var t = new StringBuilder(10); //variável e objeto locais vivem até a função
        for (var z = 0; z < 10; z++) { //só existe dentro deste bloco
            WriteLine(this.x * x + y * z); //desambigua e usa todas variáveis
        } //z morre aqui
        //uma tentativa de acessar z aqui produziria erro
        for (var z = 0; z < 10; z++) { //este z é diferente do outro
            t.Append(z.ToString()); //declarada fora, continuará existindo no fim do bloco
        } //z morre aqui
        txt = t; //a variável vai morrer o seu objeto sobreviverá em txt
        return x; //o valor será copiado para algum lugar, será um novo objeto igual
    } //aqui morrem x (local), y, t (não seu objeto, qua ainda tem referência)
}
static class Program {
    static int x = 10; //escopo desta classe tempo de vida da aplicação
    static void Main() { //só existe dentro desta classe
        StringBuilder t; //vive por toda função
        { //inicia um novo escopo
            var y = new Teste(); //variável e objeto têm escopo e tempo de vida deste bloco
            x = y.Metodo(3); //este x nada tem a ver com o x da outra classe, nem poderia
            t = y.txt; //o texto ainda viverá
        } //y morre aqui, seu objeto precisa viver mais porque tem uma referência para ele
        WriteLine(t); //o texto 0123456789 será impresso, ainda vive
        //não é possível acessar o conteúdo de y mais, mesmo o objeto estando vivo
        //o escopo acabou,só a referência previamente existente ainda pode acessar o objeto
    } //aqui morre t e finalmente o objeto criado por new Teste()
} //note que x não segura uma referência para o objeto, seu resultado é uma cópia
//código para demonstração simples, não faça isto em casa

Quem são os argumentos, qual a relação com os parâmetros e a relação entre esses e o escopo?
Comment: Relacionadas: [Qual a diferença entre escopo e tempo de vida?](http://pt.stackoverflow.com/q/135572/91) e [Qual a diferença entre parâmetro e argumento?](http://pt.stackoverflow.com/q/32448/91)
Comment: @rray eu já li e reli umas 10 vezes essas resposta, são completas... Mas o que não entendo... Acho que se a 1º , abordasse também a questão, o uso e a relação entre parâmetros e argumentos nesse contexto, poderia ser até duplicada, se juntar as 2 aí duplica, mas ainda assim eu fico a esclarecer a relação dos parâmetros e argumentos, no contexto de funções, bloco e escopo... De verdade ray, eu consigo entender as respostas relacionadas... mas falta um tantinho para eu entender todo esse relacionamento...
Answer:

function funcao(parametro) {
    var variavel = 1;
    return parametro + variavel * 2;
}
var x = 4;
console.log(funcao(x + 3));

Fiz em JS só porque é o mais fácil de postar aqui. Vale para qualquer linguagem, embora o escopo costume ter algumas variações em casos específicos, não nesse.
Função
funcao é a função :P, este é um identificador que referencia um bloco de código a ser executado. Esse identificador funciona como uma constante onde o seu valor é o endereço de onde está o código dessa função. Então quando o código chamar a função haverá uma instrução para desviar o fluxo de execução do algoritmo para o local onde está esse código.
Essa constante pode ter escopo global (toda a aplicação enxerga esse nome), ou pode estar confinado a um módulo, classe, etc. Então você só pode chamar a função se ela estiver em escopo que aquele trecho de código que faz chamada tem acesso naquele momento.
Há uma forma e declarar funções em linguagens, especialmente em JS, onde esse identificador é uma variável.
É comum, mas não obrigatório (porque não é matemática pura), que a função retorne um valor. Isso costuma ser feito com o comando return. Ele é usado para encerrar o fluxo de execução da função, geralmente devolvendo para quem chamou um resultado.
Wikipedia.
Parâmetro
Essa função tem declarada entre os parênteses uma variável chamada parametro. Sim, ela é uma variável local à função, só tem o escopo e tempo de vida equivalente ao tempo de execução da função, só existe dentro dela. Mas é uma variável especial, ela é chamada de parâmetro porque receberá um valor no momento da chamada dela.
Wikipedia.
Argumento
Quando chama a função, além de desviar o fluxo de execução para o código dela, é passado um valor para ela, esse valor é é um argumento.
Se não existisse escopo, ou seja, se todas variáveis fossem visíveis na aplicação toda, o que seria terrível para lidar com isso, então seria quase como fazer isso:
function funcao() {
    var variavel = 1;
    return parametro + variavel * 2;
}
x = 4;
parametro = x + 3;
console.log(funcao());

O argumento pode ser uma expressão qualquer, pode ser um valor, pode ser uma variável ou um cálculo que gere algum valor.
Entenda a diferença entre parâmetro e argumento.
Não podemos dizer que o argumento tenha escopo, afinal ele não tem um identificador, o seu tempo de vida é só o tempo em que ele foi criado. Não confundir argumento com uma variável que está sendo usada como único elemento de uma expressão usada como argumento. Uma variável sendo usada como argumento é algo apenas circunstancial.
Note que no exemplo o argumento é o valor resultado da expressão x + 3.
A função funcao() retorna um valor que é usado como argumento para a função log() do objeto console.
Wikipedia (no artigo sobre parâmetro tem informações mais específicas para computação).
Variável
A variável é apenas um identificador, portanto um nome para um endereço da memória onde existe um valor. Para o computador isso não interessa, é só uma forma do programar enxergar melhor o que está fazendo. Variável é uma forma de armazenamento de valores com um nome associado. Podemos dizer que ela é só um padrão de projeto para facilitar o acesso à valores na memória, tão usado que ninguém enxerga como um padrão de projeto.
Função também é um padrão de projeto para segregar um conjunto de códigos e criar uma indireção para sua execução. Na verdade tudo o que você faz são padrões de projeto encrustados na sintaxe da linguagem para facilitar sua vida.
Quando é uma variável e essa guarda uma referência para um objeto há uma semântica própria já que qualquer alteração no objeto referenciando em parametro afetará o que está na variável do argumento. Mas não é o caso do exemplo.
No exemplo há uma variável local à função, além do parâmetro, chamada variavel, Ela não é necessária ali, foi criada só para dar um exemplo. Depois ela é usada na expressão que produzirá o resultado desejado.
Também há uma outra variável chamada x, também só criada para dar exemplo, que tem escopo toda a aplicação nesse exemplo simples. Isso vale para JavaScript, não é ideal que seja assim. Se estivesse dentro de uma função, o escopo seria apenas dentro da função. Isso pode ser visto no exemplo um pouco modificado:

function funcao(parametro) {
    var variavel = 1;
    console.log(x); // <========= idealmente não deveria ser acessível aqui
    return parametro + variavel * 2;
}
var x = 4;
console.log(funcao(x + 3));

Wikipedia.
O que acontece quando chamamos uma função?.
Valor
Valor é o que se guarda na variável, o que tem dentro do seu objeto. Variáveis que são tipo por valor tem o valor na própria variável. Quando ela é de um tipo por referência o valor na verdade é a referência (ponteiro) e o valor que interessa mesmo está em um objeto em outro lugar.
Veja mais em Alocação de memória em C# - Tipos valor e tipos referência.
É comum um valor ser definido por um literal, mas em muitos casos ele é obtido de outras formas através de expressões.
Exemplo usando uma variável por referência onde o objeto é alterado:

function funcao(parametro) {
    parametro.a = 3;
    return parametro.a + parametro.b;
}
var x = { a : 1, b : 2 };
console.log(funcao(x));
console.log(x.a);

Coloquei no GitHub para referência futura.
JavaScript passa a referência, mas ela é imutável, você pode apenas mudar objeto, mas não a própria referência. Outras linguagens permitem que o objeto seja trocado por completo. Mas isso é característica específica.
Note que o escopo das variáveis não mudam, mas o tempo de vida do objeto muda e é dependente de como o algoritmo é executado. O tempo de vida das variáveis também não mudam.
No exemplo inicial 1, 2, 3, e 4 são literais com valores. O return tem uma expressão que gerará um outro valor (ele não é guardado em variáveis, não precisa, mas ele está na memória e depois pode ser atribuída a uma variável, mas é um passo independente. O argumento é formado por um valor que também é obtido com uma expressão e não está em variável ali, é apenas passado para a função. O resultado da função é um valor que equivale ao que foi calculado na função na linha do return.
Wikipedia.
Escopo
Já linkei onde pode ter detalhes (não vou repetir aqui, se tem dúvidas específicas que não ficaram claras, pode comentar lá ou até colocar uma recompensa pedindo melhorias ou novas respostas), mas é só onde um determinado identificador está visível no código, ou seja, onde ele pode ser usado e será válido.
Dependendo da linguagem o escopo pode ser a função, a classe, um bloco de código específico (comumente o que está entre chaves), módulo (ou namespace), até mesmo a aplicação toda. O que é declarado ali dentro não pode ser visto fora dessa área do código.
Escopo é um conceito de codificação. Ele não importa durante a execução, isso é totalmente abstraído. O tempo de vida é o que importa durante a execução.
O escopo tem a ver com identificadores.
Wikipedia.
Identificador
É o nome que se dá para um objeto qualquer (num sentido amplo, não importa o que seja esse objeto). Em geral ele precisa ser único em um escopo (uma região do código). Há regras do que pode ser usado nesse nome. Ele é usado para dar uma identidade para o objeto.
Também chamamos de símbolo.
Wikipedia.
Literal
É uma sintaxe que representa de forma explícita e direta um valor. Ele é o valor na sua forma mais "pura". É mais comum ser visto em objetos simples como inteiros e decimais (ex.: 123, 456.78), mas também é usado em alguns mais complexos, como string ("texto aqui"), array e objeto - no sentido de estrutura de dados - ({ 1, 2, 3 }, sintaxe que serve para os dois, depende da linguagem) e alguns consideram até mesmo outros objetos de forma mais nominal (DateTime(2016, 11, 03)), mas isso não é consenso.
Wikipedia.
Expressão
É a combinação de um ou mais valores, constantes, variáveis, operadores, e funções que a linguagem interpreta de acordo com certas regras e cria um resultado (é feito um "cálculo") que é um novo valor. O processo que calcula esse valor é chamado de "avaliação".
Wikipedia.
Comment: Muitas vezes dúvidas específicas, rodeiam uma maré de termos e condições, mas sempre que a linguagem ou inspiração me permitem, eu procuro ser específico e objetivo... Vlw a força.
Comment: O ponteiro seria o atributo do objeto,  ou viajei ?
Comment: @MagicHat em JS você não vê o ponteiro nunca. Para isso teria que fazer em C, C++, ou linguagens assim, de médio nível. Em JS o ponteiro está lá, mas você não o vê ou manipula ele. Veja um exemplo em C onde o ponteiro é manipulado diretamente: http://ideone.com/DVsU51
Comment: Tá vendo, quando eu falo que C é orientado a objetos, todo mundo me zoa..kkk Vlw, man ...Com todo essa informação tenho certeza que se eu der uma estudada e fizer uns testes vou entender... Belo material...
Comment: @MagicHat se tiver dúvidas específicas, poste.
Comment: Seria `$this`, um tipo de ponteiro em JS ?
Comment: O `this` em todas as linguagens costuma ser um ponteiro para o objeto. Uma coisa que eu falo que para aprender direito mesmo é sempre melhor aprender da base pra cima, onde se entende como o computador funciona, porque existe cada coisa, e aí as abstrações que vão sendo construídas em cima disto, mas hoje quase todo mundo aprender decorar uma casa que não tem nem alicerce. Procurando saber essas coisas, abrem portas para saber como usar as coisas da forma correta. Falo um pouco sobre isso em http://pt.stackoverflow.com/q/161846/101.
Answer: Função
Uma função pode ser vista como um contentor de instruções, ela por si só não faz nada. Apenas executa as instruções quando é chamada.
Parâmetros e argumentos
Como o @rray comentou a diferença entre parâmetro e argumento já está explicada na outra pergunta, mas deixo aqui a parte essencial:
Uma função pode ter parâmetros. O chamador da função, chama-a com determinados valores (argumentos) :
function foo(a/*parametero a*/){/**/}

foo(1) //chama foo com argumento 1, o parametro a toma o valor 1

Variáveis e valores
Uma variável tem sempre um identificador. As variáveis armazenam um valor. Exemplo:
var a = 1; //variável com identificador a
//a variável a tem valor 1

Escopo
Um escopo normalmente é definido entre a abertura de chaveta { e fecho de chaveta }
{
   //este é um escopo
}

Com base nesta definição você chega á conclusão que todas as funções tem um escopo também.
function foo(){
   //este éo escopo da funcao foo
}

Normalmente as variáveis pertencem sempre a um escopo e não podem ser vistas fora dele. Contudo os escopos podem ser aninhados. Os escopos filhos podem ver as variáveis do escopo pai. Exemplo:
function foo(){
   var a = 1;
   while(true){
       //este é o escopo do while;
       a++;//o while consegue ver/modificar a
   }
}

A ideia de escopo costuma ser um pouco difícil de entender a fundo. Por exemplo a última coisa que eu me apercebi em relação aos escopos é que não há nada que o impeça de definir um escopo por determinado motivo. Exemplo:
function foo(){
    {
        //este código tem uma lógica
        var a = 1;
    }
    {
        //este código tem outra lógica um pouco diferente e eu quero definir um escopo para ele
       var a = 2;
       //nao há qualquer conflito de identificadores porque sao escopos diferentes
    }
}

Com base nos comentários (e isto é importante):
Os escopos podem funcionar de forma diferente consoante a linguagem, o exemplo que acabei de dar nao se aplica a javascript por exemplo...
Comment: Bem didático, tá clareando... deixa eu ver a outra resposta... Vou entender isso hoje custe o que custar...
Comment: `var` é escopo por função, não por bloco... está errado o que foi dito ai no último exemplo.
Comment: @GabrielKatakura Eu nunca falei de `javascript` na minha resposta, ou falei?
Comment: @BrunoCosta ah, desculpe, supôs isso por costume

Quem é quem no uso de funções?


Derivative of the log with respect to a parameter and equates to zero to find the estimate

Question: I tried to figure out how to to solve the following expression for the parameter $\theta$ using maximum likelihood method:
I solve the problem (very huge so I omitted it) and then got this:
$$ -\frac{1}{\theta+1} - \log(uv)
- \frac{1}{\theta^2} \log\left(u^{-\theta}+v^{-\theta}-1\right) - \left(2+\frac{1}{\theta}\right) \log\left(u^{-\theta}+v^{-\theta}-1\right) = 0$$
I would like to find the estimate of $\theta$
Any help please?
Comment: Is this the first order condition for the maximum likelihood problem? It does not look like it will have an analytic solution to me. Probably your best bet is to solve the original maximum likelihood problem numerically.
Comment: You might want to clean up your formula a bit so it's easier to read.  If you can't solve for theta analytically, then you can find *a* zero of your equation quickly using Newton's method.
Comment: This is the simplest formula. So, I cannot simplify it more than this.
Comment: What I mean is the formatting of the LaTeX is poorly done.
Comment: I really do not know how to use latex here, any help will be great.
Comment: Ok, so like I said I think your best bet if you can't solve it analytically is to use an iterative method like Newton's method.
Comment: Thanks a lot. I think also, we can leave it as it and solve it numerically.
Comment: This is the first order derivative with respect to $\theta$.
Answer: Numerically, finding maxima (or minima) is generally easier than root finding, so your best bet is numerical optimization directly on the log likelihood function.


How to use Application/Assembly properties

Question: I'm writing a two-project solution with a class library designed for re-use, and an application which will consume said class library.  The library has a Properties file which is needed both in the library itself and in the application.  Unfortunately when I tried to implement this the "obvious" way, by keeping the properties in the Class library and accessing it from the application by fully specifying LibraryName.Properties..., it failed (which only goes to show that instinct is a poor substitute for knowledge).
I'm getting the following error:
System.Configuration.ConfigurationErrorsException was unhandled
  Message=Configuration system failed to initialize
  Source=System.Configuration
  BareMessage=Configuration system failed to initialize
  Line=0
  StackTrace:
       at System.Configuration.ConfigurationManager.PrepareConfigSystem()
       at System.Configuration.ConfigurationManager.GetSection(String sectionName)
       at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
       at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
       at System.Diagnostics.DiagnosticsConfiguration.Initialize()
       at System.Diagnostics.DiagnosticsConfiguration.get_IndentSize()
       at System.Diagnostics.TraceInternal.InitializeSettings()
       at System.Diagnostics.TraceInternal.get_Listeners()
  InnerException: System.Configuration.ConfigurationErrorsException
   Message=Unrecognized configuration section userSettings. (C:\Users\CPFOHL\AppData\Local\CompanyName\ProductName.vshost.exe_Url_irhjcfvtmdm11v2ub0re3en5hgllqjz4\10.0.0.0\user.config line 3)
   Source=System.Configuration
   BareMessage=Unrecognized configuration section userSettings.
   Filename=C:\Users\CPFOHL\AppData\Local\CompanyName\ProductName.vshost.exe_Url_irhjcfvtmdm11v2ub0re3en5hgllqjz4\10.0.0.0\user.config
   Line=3
   StackTrace:
        at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
        at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
        at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
        at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
   InnerException:

The only other information I can think to share is that I have the two projects in separate solutions, and I added the Library with "Add Existing," but that doesn't feel like the error...
I'm sure there's an easy answer, let me know if I can post any extra information.

[EDIT]
I'm pretty sure that the Settings are configured correctly.  The worked until I moved them to a separate solution.  I then moved them back in and have been regretting it since...  When I click Synchronize in the Settings editor I get the following:
No user.config files were found in any of the following locations:

It then lists all the places it looked (mostly in User/CPFOHL/AppData).  I hope that helps.
Comment: I do not understand what do you mean. Have you wrote a class library that is supposed to be used by more projects? (Even outside your solution? (Like a plug-in framework?))
Comment: Config file is per executable (exe), not per library (dll).  Hope this helps.
Comment: That *could* help.  It's what I want, but I still want the Properties to work. At all.  It's crashing right now.
Comment: Are you sure your config file is ok? It appears it has problems with the "userSettings" section. If you have a custom configuration section it has to be configured correctly. See http://msdn.microsoft.com/en-us/library/2tw134k3.aspx.
Comment: Actually, it doesn't seem to exist anywhere that VS2010 knows to look for it. When I click Synchronize it yells at me for now having the correct files...let's see if I can fix that.
Answer: Can you try deleting C:\Users\CPFOHL\AppData\Local\CompanyName\ProductName.vshost.exe_Url_irhjcfvtmdm11v2ub0re3en5hgllqjz4\10.0.0.0\user.config
Perhaps you changed the type on one of the properties and an old one was already persisted to the per user store.
Comment: As soon as I get in to work (or if I can find the remote desktop instructions for my company online) I'll give this a try! Thanks so much for the suggestion.
Comment: 1000 kisses upon your feet. (Ok, so maybe I'm not quite *that* excited, but thank you so much).  It regenerated what I needed.  I can't believe I didn't think to delete it...


Characterisation of DVR via invertible ideals

Question: I am reading these notes.
In terms of the proof of proposition 9.17, I understand the writer used proposition 9.5 to show this. However, to use proposition 9.5, we should check before if our local domain $A$ is of dimension one and this fact was not verified in the notes.
Comment: I'm sorry, but in the document you mention there is no proposition 9.7 — numbering is continuous, and there's only an Exercise 9.7.
Comment: I am so sorry. I just amended it.
Comment: Which direction are you asking about?
Comment: Don't be sorry: typos happen to all of us :o)
Answer: If $\mathfrak m$ is principal ($A$ local noetherian with maximal ideal $\mathfrak m$), then $\dim A\le 1$ by Krull's Hauptidealsatz (Principal Ideal Theorem).


Múltiplos callbacks com JavaScript

Question: Olá, pessoal.
Eu tenho dois callbacks de funções distintas que me fornecem valores que precisam ser utilizados fora destas funções. Segue o código:
FB.api('/me', function(response) {
    FB.api('/me/picture?type=normal', function(response) {
        foto = response.data.url;
    });
    nome = response.name;
});

console.log(foto); //Indefinido
console.log(nome); //Indefinido

Alguém sabe como posso fazer isso? Obrigado.
Comment: Possivel duplicata: http://pt.stackoverflow.com/q/60852/129
Answer: O seu código não mostra detalhes completos do que você escreveu depois daquele trecho de código, mas as chamadas a FB.api não são síncronas, logo quando você chama console.log, a comunicação com a API do Facebook ainda está em execução e suas variáveis ainda vazias.
Elas serão preenchidas num momento futuro, devido a chamada assíncrona.
Sua melhor aposta é englobar a chamada a FB.api em uma função e passar um callback. Existem muitas maneiras sofisticadas de se fazer isso, mas um exemplo bem básico, mas funcional, para você entender o contexto:
function ObtemNome(callback) {
    FB.api('/me', function(response) {
        callback(response.name);
    });
}

function ObtemFoto(callback) {
    FB.api('/me/picture?type=normal', function(response) {
        callback(response.data.url);
    });
}

function SalvarNome(nome) {
    console.log(nome);
}

function SalvarFoto(foto) {
    console.log(foto);
}

ObtemNome(SalvarNome);
ObtemFoto(SalvarFoto);

Answer: O problema pode ser uma coisa simples ou uma coisa complexa, mas no que eu estou vendo parece que você não declarou as variáveis fora da função. Eu sugiro que faça algo assim e veja se continua tendo uma saída undefined:
var nome;
var foto;
FB.api('/me', function(response) {
    FB.api('/me/picture?type=normal', function(response) {
         foto = response.data.url;
    });
     nome = response.name;
});

console.log(foto);
console.log(nome);
Métodos Internos, geralmente tem saídas internas, mas vc pode fazer uma saída externa chamando um outro método, conforme o exemplo abaixo:
var valores = [];
FB.api('/me', function(response) {

    FB.api('/me/picture?type=normal', function(response) {
         valorEntrada(response.data.url, 0);
    });
      valorEntrada(response.name, 1);
});

function valorEntrada(valor, pos) {
   valores[pos] = valor;
}

function valorSaida(pos) {
  return valores[pos];
}

var foto = valorSaida(0);
var nome = valorSaida(1);

console.log(foto);
console.log(nome);

Comment: eu já havia tentado declarar as variáveis antes, esse método não funciona. O segundo método parece válido, mas consegui resolver o problema de uma outra forma.

Obrigado por responder!
Comment: Beleza, aqui tem um bom conteúdo sobre jQuery:
http://www.academia.edu/6245365/Fundamentos_de_jQuery_jQuery_Fundamentals
Answer: Consegui resolver adaptando a solução do AlfredBaudisch. Meu código ficou assim:
    function userInfo(callback) {
        FB.api('/me', function(response) {
            callback(response);
        });
    }

    function userFoto(callback) {
        FB.api('/me/picture?type=normal', function(response) {
            callback(response.data.url);
        });
    }

    userInfo(function(info) {
        userFoto(function(foto) {
            dados = {
                nome: info.name,
                email: info.email,
                facebookId: info.id,
                foto: foto,
            }
            //Faço as operações desejadas com os dados aqui
        });
    });

Obrigado, pessoal

Múltiplos callbacks com JavaScript


Setting $order_item->setUnitPrice($price, TRUE);) stops cart items being merged, how to prevent this?

Question: Drupal Commerce 2, with Drupal 9.
In the CART_ENTITY_ADD event, if i set $order_item->setUnitPrice($price, TRUE); identical items added to the cart get added as new order items, but I want them to be merged.
If I comment out this line in my code the items get merged as expected and their quantity is summed.
How do i set the unit price without the order items being treated as distinct order items?
Relevant code of the CART_ENTITY_ADD event:
public function addToCart(CartEntityAddEvent $event) {
    $order_item = $event->getOrderItem();
    // update order item
    $order_item->setUnitPrice($price, TRUE);
    $order_item->save();
}

Comment: Let me see the whole picture. Can you post the entire code that gets runned on the `CART_ENTITY_ADD` event?
Comment: Hey @No Sssweat - I've updated my question with the full code. I don't think most of the code is relevant to the issue, as when I remove the $order_item->setUnitPrice($price, TRUE); line it works as expected and the items and quantities are merged. I think the Commerce OrderItemMatcher must not want to merge items when the unit price is set like this?
Answer: Hmmmmmmm rather than order_item->save();, try using the cart manager
// get the cart
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
// update the cart
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$order_item->setUnitPrice($price, TRUE);
$cart_manager->updateOrderItem($cart, $order_item);

Bonus: Some methods/functions you might find useful.
Comment: Thanks for the reply. I actually ended up moving the pricing logic into a price resolver instead. Thats probably where it should belong anyway. Everything works properly when the pricing logic is moved out of the CART_ENTITY_ADD event and into the price resolver.


Geometric progression - How many members? a=7, r=4, Sum=7340025

Question: In Geometric Progression, first member is equal to 7 and the common ratio is equal to 4. How many members should be taken in to the sequence that it would amount to 7340025?
Comment: 7*(4^(10)-1)=7340025 and the sum of the n first terms of the sequence is 7*(4^n-1)/3 hence no partial sum equals 7340025, the closest one being the sum of the 10 first terms 7*(4^(10)-1)/3=2446675 and the sum of the 11 first terms 7*(4^(11)-1)/4=9786707. (No member of the sequence is 7340025 either, the closest one being the eleventh term 7*4^(10)=7340032.)
Answer: If the answer is given, I bet it is $10$. But in fact there is no answer, one number in the problem is wrong.
The sum of the first $n$ terms of the generic geometric progression is given by
$$a+ar+ar^2+\cdots+ar^{n-1}=\frac{a(r^n-1)}{r-1}.$$
Put $a=7$, and $r=4$.  We want to find $n$ such that
$$\frac{7(4^n-1)}{3}=7340025.$$
Easily we find that $4^n=(3/7)(7340025)+1$.
Let's do the arithmetic.
We get a number which is not an integer power of $4$.  Since $n$ must be an integer, the problem cannot be solved, there is no geometric progression with the desired property. (This was pointed out in the comment by Didier Piau.)
But now in the calculation, let's do the division by $7$, but forget to multiply by $3$.  Equivalently, let's use the wrong formula for the sum of a geometric progression, and forget about the $r-1$ in the denominator.
Then we get $4^n=1048576$. Note that $1024^2=2^{20}=4^{10}=1048576$. So the conclusion is that $n=10$.
Or else everything was done right, except that $r=2$ was used in the calculation.
Whoever made up the problem naturally started from the desired answer of $n=10$. Then the person worked backwards using the formula. So first (s)he subtracted $1$, then multiplied by $7$, then forgot to divide by $3$, or worked from the wrong formula.  Or else the backwards calculation started from $2^{20}$, which is $4^{10}$, and the person didn't realize that summing consecutive powers of $4$ is not the same as summing consecutive powers of $2$.
Comment: @BeatShot:  it is not so rare-mistakes creep in.  If you think you can solve the problem, see if you can check it.  In this case, a quick spreadsheet would show the behavior André Nicolas describes and would give confidence that you are right and the book is wrong.
Comment: I can't believe this has happened to me twice (Error/Mistake in the problem itself). Thank you for answering Andre.


SCOM Maintenance Mode

Question: SCOM supports putting discreet objects/classes/targets into maintenance mode.  This gives a very fine control over what objects/classes/targets have alerts forwarded or not.
Unfortunately, behaviorally, our operations team doesn't want that level of control.

Behaviorally they want to put the entire server, or groups of
  servers, into maintenance mode.  Where "maintenance mode" means no
  alerting of any kind.  Period. Fin.

Today, we come close, by putting WindowsComputer and HealthService (which also seems to cover Agent).  Putting those objects into maintenance mode allows us to do application deployments (service stops, etc) and anything requiring a reboot.
However, we still get occasional alerts from objects in either like the Dell MP or BizTalk MP. Alerts that don't tend to target WindowsComputer, or anything in its inheritance chain(?).
We tried putting Entity object/class/target into maintenance mode but this seemed to send the RMS server into a tizzy. e.g. If we made 50 requests, for 50 different servers, maybe 1 in 5 would actually be placed into maintenance mode.  The remainder would be ignored.
We are using the SCOM API via Power Shell, or the SCOM SDK object model, to put things into maintenance mode.
Is there a recommended way to put a server, and all its contained objects, into maintenance mode, reliably?
Is there something our team should be considering on why we don't want to put everything into maintenance mode?
Answer: According to the documentation, you can easily place a whole server in maintenance mode:

In the Operations console, click the Monitoring button.
In the Monitoring pane, expand Monitoring, and then click Computers.
In the Computers pane, right-click the computer that you want to place into maintenance mode, click Maintenance Mode, and then click Start Maintenance Mode. You can use ctrl+click or shift+click to select multiple computers to place into maintenance mode.
In the Maintenance Mode Settings dialog box, under Apply to, click Selected objects only if only the computer is to be placed into maintenance mode; otherwise, click Selected objects and all their contained objects.
Comment: For the most part, this seems to work for rules/monitors targeting WindowsComputer or some derivative. This doesn't work as we expected if the machine down is for any significant length of time: reboot, hardware maintenance, etc.  We get Health Service Watcher Alerts because RMS can't talk to the agent (or something similar) because  HealthService is not part of the WindowsComputer inheritance chain and at least Dell MP and BizTalk MP also have several objects not inheriting from WindowsComputer.  Just to throw in a wrench, we often use the API (from admin/deploy scripts) :)
Comment: I'll try your suggestion though as if we use the console, we are using views specifically created for admin teams.
Comment: *facepalm* this works as advertised with 2007 R2.  Testing bore this out.  We will be further investigating the reports of this not working to see if we can narrow down to a repeatable scenario.
Answer: This article might help clarify a few things:
http://blogs.technet.com/b/momteam/archive/2012/05/23/kb-understanding-operations-manager-maintenance-mode.aspx

Is there a recommended way to put a server, and all its contained objects, into maintenance mode, reliably?

Putting the computer object into maintenance mode should work.
Since SCOM 2007 R2 there is no need to separately put the agent and agent watcher into maintenance mode. Just be sure to check the 'Selected Objects and all their contained objects' option if using the console, or the TraversalDepth.Recursive if using the SDK (the PowerShell cmdlet does this by default).

However, we still get occasional alerts from objects in either like the Dell MP or BizTalk MP. Alerts that don't tend to target WindowsComputer, or anything in its inheritance chain(?).

You could try to identify the top-level distributed applications (DAs) or groups that contain the objects raising the alerts, and put those DAs and groups into maintenance mode.

Is there something our team should be considering on why we don't want to put everything into maintenance mode?

Consider:

Putting everything into maintenance mode can take a long time
Putting the RMS into maintenance mode is normally a Bad Thing - 'Configuration distribution, the heartbeat feature, and other features for the system might become unreliable' (see article above)
Comment: +1 for the excellent article.  In the link, there is a link to known issues, one of which is getting heart beat alerts which *says* its still applicable to 2007 R2, but my testing did not bear that out.  I'll wait and see if I get any more reports from the wild so I can better narrow down the scenario.

SCOM Maintenance Mode


In C#, can I use reflection to determine if an enum type is int, byte, short, etc?

Question: Is this possible?  I can't find it anywhere.
Comment: For WinRT: type.GetTypeInfo().IsEnum;
Answer: Try this:
<code>Enum.GetUnderlyingType(typeof(YourEnum))
</code>


Axios returns index.html content to frontend (React.js)

Question: I am trying to build a web application where I am using React.js for frontend and Flask as the backend. I tried to establish a connection between the frontend and the backend by stating the proxy server in React and CORS in Flask. It works fine in the dev environment. However, when I tried deploying the same code on Heroku any request from frontend would only return index.html junk. I read somewhere that proxy is just meant to be used for development propose and does not work in production. Is there any other alternative that I can try to make this work?
Below is a sample of the data returned by axios -
<!doctype html><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>React App</title><link href="/static/css/main.43a4cdf3.chunk.css" rel="stylesheet">You need to enable JavaScript to run this app.

Axios get request -
  return new Promise((resolve, reject) => {
    axios
      .get('/auth/redirect')
      .then(res => resolve(res.data), err => reject(err));
  });

Comment: That code that axios gets is the code that the page is supposed to render in the first place.
Answer: So I found out on debugging that the application was proxying to itself and all the requests were redirected to the client. I later changed my Axios call to
 return new Promise((resolve, reject) => {
    axios
      .get(base_server_url+'/auth/redirect')
      .then(res => resolve(res.data), err => reject(err));
  });

and it worked!
Answer: Please post your backend code
axios will add current route to url,
so if your current route is /home,
axios may fetch servername+ /home/auth/redirect
you can check url which axios fetch in console
Answer: export const fetchPrivacyPolicy = (cb) => {
return (dispatch) => {
 axios.get(APIENDPOINT + "privacy_file").then((res) => {
  if (res.status == 200) {
    cb(res.data);//res data is actually the html content
  }
 });
};
};

import React from "react";

function PrivacyPolicy(props) {
  const [content, setContent] = React.useState(``);

  React.useEffect(() => {
     props.fetchPrivacyPolicy((htmlText) => {
       setContent(htmlText);
     });
  }, []);

  return
;
}

export default PrivacyPolicy;


Email server - redundant, mobile, and secure

Question: Post deleted deleted deleted deleted deleted
Comment: Zero downtime is a myth. Sorry, but it's an impossibility. Look at how much money Amazon/Google/et. al. Have to throw at their infrastructure and development, and they still have downtime.
Comment: @FEAST email is more complicated than you think it is (As an example, you state your gmail account "hasn't dropped an email in 5 years" -- If you truly understand email you know there is no way you can make that statement with any degree of confidence). The notes on the linked questions will help get you thinking in the right direction, but reliable redundancy is a hard thing to achieve. This something you should spec and design carefully rather than "blindly attack".
Comment: I should also mention...it's obvious you have a *lot* to learn about systems administration, networking and email services. I would strongly recommend that you start with a single email server. Run that for long enough for you to feel comfortable with its operation, backup, restore, etc. If you go forward with the system you propose, you'll quickly get underwater, and all the redundancy, security, and reliability you desire will be squandered.
Comment: @FEAST - that comment highlights how much you need to learn about email. If your server is down and someone sends you an email, it will not be lost. SMTP was designed with non-reliable networks in mind. If the sending sever is not able to deliver to the MX, it'll just queue the email and retry. Most will retry several times, up to 48 hours before sending an NDR to the sender. If your server comes up before the message timeout, your message will be delivered without issue.
Comment: In addition to the question noted above, you should take a look at http://serverfault.com/questions/130300/reaching-99-9999-uptime
Comment: Well good luck to you sir. The problem is not getting things working. That's quite easy. The problem is being able to quickly diagnose and recover from issues. *Thats* the hard part, and that only comes from years of experience.
Comment: @voretaq - that's why I'm here.  I'm not looking to implement immediately careful design is all part of the process - as for right now I am just trying to get the ball rolling.  Also, if I missed an important email - I would find out relatively quickly - and it's just never caused an issue.  MY servers will be fresh yo.
Comment: Ya so I will learn.
Comment: Also sorry if I was a jerk yesterday, I'm new here.
Answer: Avoid "reinventing the wheel"...
It's possible to obtain high-availability mail through less-complication means.
There are some redundancies already built into the SMTP protocol (retries, MX priority, etc.). You can get much of the same protection by using a backup MX that can spool if your primary delivery system is unavailable.
IMAP does what you're asking in terms of synchronization. Microsoft Exchange MAPI is a little more elegant.
The path of least resistance (and $cost) is probably obtaining an account on a hosted service, for example, hosted Microsoft Exchange available through any number of cloud providers. Let them handle the redundancy. It doesn't have to be Microsoft. There are plenty of Linux-based mail hosting solutions available, too.
See:
How to make sure that in case of our mail server being unreachable (connection down) mail still gets queued and resent once it's back up?
How to build a high availability Postfix system?
Comment: By spool, I mean that you can use a backup external MX relay or service to hold mail in the event that your primary mail server is down. See my edits above.


Why do referees raise their arm on three-point field goals?

Question: While watching a highlight video of three-point field goals in the NBA, I noticed the referees raise their arm after the ball leaves the shooter's hands and through the duration of three-point field goals. Why do referees raise their arm on three-point field goals?
Answer: In the NBA, WNBA, NCAA and internationally under FIBA rules, the referee is required to raise his arm when a three point field goal is being attempted. If the player on the court makes the three point field goal, the referee is required to hold up his other hand to signal to the score keeper that the player has made the field goal. The actual signal differs slightly between the NBA and WNBA, where the referee is simply required to raise their hand(s), and the NCAA and FIBA rules where the referee is required to raise their hand(s) with three fingers extended.
This video gives a visual explanation of the three point shot hand signal: VIDEO

The NBA signal can be seen on page 66 the 2013-2014 Rule Book:

The FIBA signal can be seen on page 58 of the 2014 Official Basketball Rules.
Comment: The key words being "to signal to the score keeper".  That's really the intention behind most signals.  Signals weren't originally made for audience understanding, but to communicate between officials, and in certain circumstances to notify players\teams.  Note how many signals in https://www.nfhs.org/media/1015648/basketball-signal-chart.pdf show something a scorer\timer would need to know, and how wildly different\exaggerated competing signals are.
The score keeper is not allowed to judge whether it was worth 2 or 3 (or make any judgements at all), only rely upon the signal of the referees.


How to replace numbers in text with numbers in the array with AHK?

Question: Clipboard content = 10,19,2023,19,6,2,9   (this is a variable array)
Sentence with numbers to modify:
From 4  to 6 July 2023, we attended 10 meetings, including 5 discussions, 25 exhibits and 3 briefings.
Modified Sentence:
From 9  to 9 July 9, we attended 9 meetings, including 9 discussions, 9 exhibits and 9 briefings.
The problem:  only the last number in the array is applied correctly.  Any idea how to fix my code? Thanks
<code>^!2::
    ClipSaved := ClipboardAll
    Clipboard :=
    Send, ^x
    ClipWait, 2
    CutText := Clipboard
    Clipboard := ClipSaved
    regex := "\b\d+\b"
    replacedText := CutText
    Loop % copiedNumbers.Length()
    {
    replacedText := RegExReplace(replacedText, regex, copiedNumbers[A_Index])
    }
    Clipboard := replacedText
    Send, ^v
return
</code>
Comment: @Wiktor Thank you for the suggestion. That did not solve the problem. It only made the clipboard content to be pasted repeatedly according to the number of items in the array. In this case 7 times.
Comment: OK, so you want to replace *any* number in the text with `9`, right? Then why use the loop in the first place? Just use `replacedText := RegExReplace(replacedText, regex, copiedNumbers[A_Index])` once, shouldn't it work already?
Comment: @Wiktor No. Numbers in the array (10,19,2023,19,6,2,9) should replace numbers in the sentence to modify. 10 should replace 4; 19 should replace 6 and so on2 ... The problem is the last number in the array is used to replace everything.
Comment: I see now. I doubt this is possible in AHK. In other languages, there is a way to pass the match to an anonymous function used as a replacement argument, and here, I do not think it supports such function arguments.
Answer: You can achieve it like this in ahk v2:
<code>variable := "10,19,2023,19,6,2,9"
text := "From 4 to 6 July 2023, we attended 10 meetings, including 5 discussions, 25 exhibits and 3 briefings."

replacedText := RegExReplace(text, "(.*?)\d+", "$1*")

for i, v in StrSplit(variable, ",") {
    replacedText := RegExReplace(replacedText, "(.*?)\*(.*)", "$1" . v . "$2")
}

MsgBox(replacedText)
</code>
You replace all occurrences of numbers in the original string with "*" and then for each number in your "variable array" you replace a single star until there are no numbers left. This doesn't account for a mismatch in the amount of numbers in the string and variable array however.