Instalar o Codeigniter 3 com Doctrine e Composer

Question: Qual a melhor maneira de instalar o doctrine via composer no codeigniter 3.0? Pretendo deixar os arquivos na pasta libraries.
Criei o arquivo composer.json:
{
    "config": {
        "vendor-dir": "application/libraries"
    },
    "require": {
        "doctrine/common": "2.4.*",
        "doctrine/dbal": "2.4.*",
        "doctrine/orm": "2.4.*"
    }
}

Executei o comando php composer.phar install, criando os arquivos dentro da pasta application/libraries no Codeigniter 3.0.
Criei um library chamada Doctrine.php e adicionei no autoload:
$autoload['libraries'] = array('doctrine');

O doctrine.php:
<?php
//AutoLoader do Composer
$loader = require __DIR__.'/vendor/autoload.php';
//vamos adicionar nossas classes ao AutoLoader
$loader->add('Pasta_library', __DIR__);

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;

//se for falso usa o APC como cache, se for true usa cache em arrays
$isDevMode = false;

//caminho das entidades
$paths = array(__DIR__ );
// configurações do banco de dados
$dbParams = array(
    'driver'   => 'pdo_mysql',
    'user'     => 'root',
    'password' => '',
    'dbname'   => 'dnp',
);

$config = Setup::createConfiguration($isDevMode);

//leitor das annotations das entidades
$driver = new AnnotationDriver(new AnnotationReader(), $paths);
$config->setMetadataDriverImpl($driver);
//registra as annotations do Doctrine
AnnotationRegistry::registerFile(
    __DIR__ . '/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'
);
//cria o entityManager
$entityManager = EntityManager::create($dbParams, $config);

Ao tentar subir o projeto, aparecem as mensagens de erro:

Fatal error: require(): Failed opening required
  '/Users/israel/Sites/agemed/application/libraries/vendor/autoload.php'
  (include_path='.:/usr/local/php5/lib/php') in
  /Users/israel/Sites/agemed/application/libraries/Doctrine.php on line
  3

Mostrando que o sistema não está localizando o caminho correto.
Onde corrigir?
Comment: o Doctrine.php esta em qual pasta do projeto ?
Answer: TL;DR
Subi no GitHub um projeto exemplo integrando o CodeIgniter 3 com o Doctrine, acompanhado de um exemplo.

O erro está na maneira que você utiliza o autoloading.
No arquivo doctrine.php o correto na linha 3 seria:
$loader = require APPPATH . 'vendor/autoload.php';

Porém incluir na unha o autoload  dentro do Doctrine.php é desnecessário no Codeigniter 3. Ele possui uma configuração que já injeta o autoload do Composer na nossa aplicação.
Configure o arquivo config.php
$config['composer_autoload'] = TRUE;

Ou se preferir utilizar a pasta vendor na raiz do projeto (meu caso), insira o caminho para o autoload.php.
$config['composer_autoload'] = 'vendor/autoload.php';

Utilizando a segunda opção podemos tirar do nosso composer.json a config "vendor-dir" : "application/libraries".

Meu arquivo libraries\Doctrine.php é um pouco diferente também. Utilizei um arquivo baseado nessa resposta do SOen.
<?php

use Doctrine\Common\ClassLoader,
    Doctrine\ORM\Tools\Setup,
    Doctrine\ORM\EntityManager;

class Doctrine
{
    public $em;

    public function __construct()
    {
        // Load the database configuration from CodeIgniter
        require APPPATH . 'config/database.php';

        $connection_options = array(
            'driver'        => 'pdo_mysql',
            'user'          => $db['default']['username'],
            'password'      => $db['default']['password'],
            'host'          => $db['default']['hostname'],
            'dbname'        => $db['default']['database'],
            'charset'       => $db['default']['char_set'],
            'driverOptions' => array(
                'charset'   => $db['default']['char_set'],
            ),
        );

        // With this configuration, your model files need to be in application/models/Entity
        // e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
        $models_namespace = 'Entity';
        $models_path = APPPATH . 'models';
        $proxies_dir = APPPATH . 'models/Proxies';
        $metadata_paths = array(APPPATH . 'models');

        // Set $dev_mode to TRUE to disable caching while you develop
        $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies_dir);
        $this->em = EntityManager::create($connection_options, $config);

        $loader = new ClassLoader($models_namespace, $models_path);
        $loader->register();
    }
}

Para utilizar o Doctrine, crie uma pasta Entity dentro de models e insira ali dentro suas Entities dentro do namespace Entity
<?php namespace Entity;

/**
 * @Entity @Table(name="products")
 **/
class Product
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $name;

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

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

Após incluir o Doctrine.php no autoload do Codeigniter ($autoload['libraries'] = array('doctrine');) posso utilizar a Entity no meu controller.
public function index()
{
    $product = new Entity\Product();

    $product->setName('Teste');

    $this->doctrine->em->persist($product);
    $this->doctrine->em->flush();
}

Comment: Israel, conseguiu entender a ideia?


g++ - Terminal Memory Allocation

Question: I've compiled and am currently running a program with g++. I expect that it's going to take a while to run but I'm hoping I might be able to speed it up. I'm currently using Ubuntu. Checking the system monitor I found the terminal I'm running the program from. While it certainly is using a chunk of memory, there's far more memory available. Is there some sort of command for the terminal or something that will allow me to allocate more memory to the program so it will run a bit faster? Or a command for g++? Or just something to put in the C++ code?
Thanks!
Answer: Giving the program more memory will not make it run faster; it will ask for more memory from the operating system as needed. You're thinking of the behavior of languages with garbage collection, like Java. Normal C++ programs don't include a garbage collector, and thus won't run any faster with a larger heap.
Comment: I thought this might also be the case. Thanks then.

g++ - Terminal Memory Allocation


Converted console app to Windows Forms application. But need to run the program in both Forms and Console

Question: I converted my console application to windows forms application. Now if I need to run this program in both forms and console what do i do? I tried running it as WinForms and console... in both the cases only one of them are opened. Any advice?
Comment: What about having a command line argument that sends output to the console rather than showing the UI? You would need to separate your code such that it can work without the UI (Which I assume you have already done). Fr a more detailed answer you need to provide more detail.
Answer: You have got two very different outputs which want to share the same code base for logic.
You will need to separate your application logic into a code library, then reference it from a Windows App and a Console App. In each app call the appropriate methods to perform whatever functionality you want.
Comment: This helped ! Thank you ! can you give me some link where i can learn how to separate my code to libraries ?
Answer: You can start project in Console application and add windows forms in it. I tried in my projects. :)


calculating the solid volume limited by the $xy$ plane and the surfaces $z=\frac{x^2}{2p}+\frac{y^2}{2q}$ and $x^2+y^2=a^2$ where $p,q,a ∈ R^+$

Question: help me with this excercises
calculating the solid volume limited by the $xy$ plane and the surfaces
$$z=\frac{x^2}{2p}+\frac{y^2}{2q}$$
$$x^2+y^2=a^2$$
where $p,q,a ∈ R^+$
i dont know how to start this excercises, help !!!
Answer: Start by thinking about what each surface looks like:
$xy$ plane is pretty straightforward. It is $z=0$.
$x^2+y^2=a^2$ is 2D would describe a circle with radius $a$ so in 3D it describes a vertical cylinder with radius $a$.
$z=\frac{x^2}{2p}+\frac{y^2}{2p}$ is harder to visualize by we can tell that $z$ here is a function of $x$ and $y$ and that is it always non-negative so it must be above (or equal to) the $xy$ plane. So your integral can be written as:
$$\iint_{x^2+y^2=a^2}\frac{x^2}{2p}+\frac{y^2}{2p}dA$$
To evaluate it:
From the shape using polar coordinates is going to make it easy. So rewrite $x=r\cos\theta$ and $y=r\sin\theta$. The integral becomes:
$$\int_0^{2\pi}\int_0^a \left(\frac{(r\cos\theta)^2}{2p}+\frac{(r\sin\theta)^2}{2p}\right)r\,dr\,d\theta$$
$$=\frac{2\pi}{2p}\int_0^a r^3\left(\cos^2\theta+\sin^2\theta\right)dr$$
$$=\frac{\pi}{p}\int_0^a r^4\,dr$$
$$=\frac{\pi}{p}\times\frac{a^5}{5}$$
$$=\frac{\pi a^5}{5p}\ units^3$$
Answer: You can use the polar form: $$x=r\cos(t),~y=r\sin(t),~ 0\leq t<2\pi$$ So we have $$z=\frac{x^2}{2p}+\frac{y^2}{2q}\longrightarrow z=r^2\left(\frac{\cos^2(t)}{2p}+\frac{\sin^2(t)}{2q}\right)$$ and the new ranges are $0\leq t<2\pi,~~ 0\leq r\leq a$. Don't forget to use Jacobian in the new integral.


What is the meaning of a double dot within a square bracket in C++

Question: In the file C:\Program Files (x86)\Windows Kits\8.1\Include\um\OleAuto.h, I found the following code that I do not know how to interpret:
WINOLEAUTAPI SafeArrayAccessData(_In_ SAFEARRAY * psa,
_Outptr_result_buffer_(_Inexpressible_(psa->cbElements *
product(psa->rgsabound[0..psa->cDims-1]->cElements)))
void HUGEP** ppvData);

Note the double period within the square bracket. Is that a new operator in C++?
Comment: I'll bet that `_Outptr_result_buffer_` is a macro, and the argument is never seen by the compiler. (If it were, it would be rejected as a syntax error.)
Comment: @KeithThompson is right. `_Outptr_result_buffer_` ultimately expands to nothing in normal compilation. The macro is used by static analysis tools.
Comment: It seems like a twisted combination of SAL expressions and probably undocumented compiler intrinsics.
Comment: It sure isnt listed here: http://en.cppreference.com/w/cpp/language/operator_precedence . This site is quite thorough otherwise
Answer: It appears to be a SAL annotation used to tell the static analyzer that the size of the buffer is too complex to represent using ordinary annotations:
https://msdn.microsoft.com/en-us/library/jj159527.aspx
It doesn't have to contain valid syntax, but what it contains is probably meant to succinctly illustrate to a human reader how the size of the buffer could be calculated.
If I'm to interpret it myself, I'd guess it means what the following code would yield:
DWORD CalculateInexpressibleSafeArrayDataSize(SAFEARRAY * psa)
{
    DWORD cbSize = psa->cbElements;
    for (int i = 0; i < psa->cDims; i++) // product()
        cbSize *= psa->rgsabound[i]->cElements;
    return cbSize;
}

Comment: And SAL is supposed to "reduce C++ defects". By writing nonsense inside hardly documented intrinsics.
Comment: @gd1: My guess is that SAL was added to that function long after it was prototyped and implemented, and then the prototype of the function couldn't be changed or removed due to backwards compatibility requirements. In general though, SAL is truly excellent and if you find declarations in your own code that cannot be sanely marked-up with SAL, that's a good indication that you should rethink what you did.


Taxonomy Term Hierarchy(not programmatically nor content related)

Question: I know there are zillion topics about this, but I just couldn't apply it to my View Block in Drupal 8. On the other hand all these Taxonomy Term Tree creation is based on content related.
Here is what I would like to do, I would like to display my "Collections" taxonomy term hierarchy without content relationship, as it is(just parent-child terms). This is how my taxonomy term hierarchy looks like:

And this is how far I could get:

This is my result(which is completely wrong):

**FYI: I am using Views Tree and I follow this Taxonomy display children with Taxonomy View Depth not working **
Thank you for help and time in advanced.
Answer: you can use the Views Tree module for this: https://www.drupal.org/project/views_tree
It works pretty well, you just need to use the Tree (list) views FORMAT, add the parent taxonomy term in RELATIONSHIPS, add the parent term's Name field to the FIELDS list, and then use it as the Parent field on the Tree settings:

The module will link the terms hierarchically and output a nested list, and you can always hide the parent term's name field to show just the children terms names.


redis celeryd and apache

Question: I'm a bit new to redis and celery.  Do I need to restart celeryd and redis every time I restart apache? I'm using celery and redis with a django project hosted on webfaction.
Thanks for the info in advance.
Answer: Provided you're running Daemon processes of Redis and Celery you do not need to restart them when you restart Apache.
Generally, you will need to restart them when you make configuration changes to either Redis or Celery as the applications are dependent on eachother.
Comment: yeah, I'm running them as Daemons .  Thanks for the advice.
Comment: Does that include when you make code changes (which is the main reason I restart Apache)?

redis celeryd and apache


LDAP Groups in authconfig

Question: In my authconfig setup, I always use :
<code>--ldapbasedn='ou=users,o=Directory'
</code>
I thought by using:
<code>--ldapbasedn='o=Directory'
</code>
groups would also be included, but no luck.
My LDAP schema looks like this:

But it doesn't seem that this includes group information.

What's the idiomatic way to include group information into authconfig?
Answer: I use ldap with a manual config, not using authconfig. Note this is not redhat/centos, but ubuntu and debian, but the config many be similar. (I use pam_ldap and nss_ldap)
I have a line in the ldap.conf which looks like this :
nss_base_group ou=group, o=Mydirectory
Comment: thanks ............ any details on how the base_group parameter works?

LDAP Groups in authconfig


What's the difference between the tritone and the blue note?

Question: For a while I thought they were one and the same, now I'm confused. This Wiki Article on the subject asserts that the blue note isn't even a real note, i.e. a note that's not part of the standard scales. Please elucidate this for me.
Comment: @ToddWilcox: The point I was making earlier is that all religious singing (or chanting) contains some form of blue notes and all other kinds of weird notes. Not to mention that singing a capella is conducive to using such notes.
Comment: I'm not sure about that Wikipedia article. For one thing I don't think the explanation of equal temperament matches my understanding of why it was developed. And there is good reason to believe the notes and scales used in early 20th delta blues are actually based on the Muslim call to prayer that was brought over by west African Muslim slaves.
Comment: @ToddWilcox: I'm not sure about the article either. As for the Muslim call to prayer: I'm not sure about that one either. The Transatlantic slave trade was banned unequivocally by Thomas Jefferson during the first month of his Presidency, unless I"m much mistaken. You're saying Muslim slaves waited nearly a whole century before introducing their tonal heritage to their music ... that's a stretch, kind of. In my opinion, anyway.
Comment: @ToddWilcox:  Here's a Wiki article on the call to prayer: https://en.wikipedia.org/wiki/Adhan It never spread to any parts of Africa, it would seem. Africans (both northern and sub-saharan) had their own deep-sitting traditions. If you listen closely to Gregorian chants, you'll find that they resemble the blues as well.
Comment: @ToddWilcox I was sure enough that the direct link to equal temperament in that way was bogus to take it out.
Comment: @Ricky Obviously slave singing ("field hollars") was not recorded while they were slaves, nor prior to the invention of recording. Even after the civil war, former slaves would not have been the first to have their music recorded, as racism and marginalization were the norm. The blues, the technology available to record it, and the will to do so all came together near the beginning of the 20th century. There is a recording of an a cappella performance by an inmate in a prison where the cadence and the melody almost exactly match the call to prayer, just the words are blues style lyrics.
Comment: The point being that I don't think the Wikipedia article about blue notes is correct in its implication that the origin of blue notes is a matter of established consensus. I heard a recording on the radio over the weekend that was a call to prayer recorded in Morocco. So either NPR was wrong or Wikipedia is wrong about it never spreading to Africa. I have a hard time seeing Islam spreading across Africa and nowhere in Africa there being a Muslim call to prayer.
Comment: http://m.sfgate.com/opinion/article/Muslim-roots-of-the-blues-The-music-of-famous-2701489.php
Answer: There's no standard precise definition of what a blue note is. In some cases, a blue note could be seen as a deviation from the pitch of the note of a 'standard' (e.g. major) scale, but in other cases, blue notes are used in music whose tonality is far enough removed from the major or minor scale that those scales are arguably not sensible reference points to measure deviations from.
The quote in the Wikipedia article seems quite good:

Like the blues in general, the blue notes can mean many things. One
  quality that they all have in common, however, is that they are lower
  than one would expect, classically speaking. But this flatness may
  take several forms. On the one hand, it may be a microtonal affair of
  a quarter-tone or so. Here one may speak of neutral intervals, neither
  major nor minor. On the other hand, the lowering may be by a full
  semitone--as it must be, of course, on keyboard instruments. It may
  involve a glide, either upward or downward. Again, this may be a
  microtonal, almost imperceptible affair, or it may be a slur between
  notes a semitone apart, so that there is actually not one blue note
  but two. A blue note may even be marked by a microtonal shake of a
  kind common in Oriental music. The degrees of the mode treated in this
  way are, in order of frequency, the third, seventh, fifth, and sixth.
— Peter van der Merwe, Origins of the Popular Style, 1989

We can see from that explanation that blue notes are not simply the use of flattened notes that themselves still belong to the 12-tone scale, as blue notes can be quarter-tone deviations, or characterised as a glide though a frequency range.
Although the idea of blue notes is not restricted to the blues scale, this question - Exact pitch of blues scale notes - has some relevant answers. In particular, you can see from my answer there that I think that there's a note in the blues scale that is - in a guitar context, at least - played as a raised fourth more than a flattened fifth, though it may depend on the style in question (and of course such a distinction would be meaningless on the piano.)
When talking about 'blue intervals', we normally mean intervals from the root - so the 'blue third' is some kind of (altered) third above the root.
A tritone is simply an interval of three tones. So we can say that a note an interval of a tritone above the root could have the same frequency as a 'blue note' played between the fourth and fifth. That's not to say that a tritone above the root is a blue fifth though - blue notes are more complex than that.
Answer: They are two different concepts completely, although the blue notes do typically take advantage of the tritone via harmony and melody.
A tritone is a specific interval of an augmented fourth (A4) or a diminished fifth (d5). It's a very special interval as it's the furthest distance in semitones you can be away from a note and it's dissonance and how it resolves is very central to a lot of compositions. A simple example from C to  F♯/G♭ is a tritone. This interval is an essential part of the dominant 7th chord as the interval between the major third and the minor seventh in the chord is a tritone.
This leads us to the blue notes. Alone it's just notes to color the melody and harmony of a song, typically in a slightly dissonant fashion. The blue notes are ♭3, ♯4, ♭5, and ♭7 that are deviations from the typical major scale. From these notes tritones can be and are typically formed between other notes in the melody and harmony, but the notes themselves are not tritones. The ♯4 and ♭5 create a tritone with the tonic note. The ♭7 makes a tritone between itself and the 3 like in the dominant 7th chord. The ♭3 makes a tritone between itself and the 6 which is also root note of the relative minor of whatever major key you are in.
However, the blue note is not just used for there tritone properties, but also other properties as well including chromatic. It's pretty much standard to hear either 3, ♭3, 2 or 5, ♭5, 4 in a blues lick.
So in short the blue notes are notes added for flavor or color that can produce a tritone, but don't need to while a tritone is a well defined interval.
Comment: How? ... Are you saying you can just come up to a piano, press _one_ key, step away, and claim (while keeping a straight face) that you've just played a blue note?
Comment: Okay, just to make sure I understand: the concept of the blue notes kind of _includes_ ... uh ... _contains_, but isn't limited to, the tritone and its uses. And Wagner's constant pounding of the tritone in _Tristan_, which keeps the listeners in tonal suspense (denying them resolution till almost the very end of the piece) is not _necessarily_ what jazz composers use the blue notes _for_. Correct?
Comment: I believe we're talking about the same thing. A blue note is also an interval. 3 is only an E if you're playing in C major; it becomes E-flat in C minor.
Comment: @Ricky the blue notes can be used to make tritones, but they alone are not tritones and have other applications such as chromaticism  and tension. A tritone is an interval not a note.
Comment: @Ricky It's **not** an interval it's a note. In the context of other notes it can be, but the note alone is not an interval.
Comment: Read my answer again it's the third paragraph. It's a color **note** in a certain context that typical causes tension. So you add the note to the harmony or melody and you may create a tritone in some contexts, others chromatic movement, and even in others a minor second clash, but the fact that the relationship between that note and other notes is a tritone sometimes doesn't make the note into an interval or make that the defining characteristic of it. The tritone naturally exists in the major scale and no one call the 4th degree or the 7th degree blue notes and there are reasons why.


U is T-invariant if and only if orthogonal complement of U is T*-Invariant

Question: as told on the topic i need to prove
if U is a subspace of V and V is a vector space. $T\in L(V)$ which L is the set of all operators.
I need to prove the both side of this statement below:
U is T invariant iff $U^\bot$ is T*-invariant
T* is adjoint operator of T and $U^\bot$ is orthogonal complement of U
i need this proof to use it to solve somthing else.
Answer: Suppose $TU\subseteq U$. Then for each $w\in U^\perp$, we have $\langle T^\ast w,u\rangle=\langle w,Tu\rangle=0$ for all $u\in U$. Hence $T^\ast w\in U^\perp$. Since $w$ is arbitrary, in turn we have $T^\ast U^\perp\subseteq U^\perp$. The argument for the other direction is similar.


React useState didn't catch previous state

Question: I have some troubles with updating state in my component:
i got few services which can be selected and selection, starts async loading this service, so i want to show some loading state, but when there is more than one service and i select both ( pretty fast ) i'm getting wrong previous state
when i'm fast click on first and second service, their both need to be loading
but actual loading state when i click on second service === {0: false, 1: true} must be {0: true, 1: true} but i can't figure out why first service loading === false
there is code
generating initial state
    const [loadingState, setLoadingState] = React.useState(
        availableServices.reduce((loadingState, service) => {
            loadingState[service.id] = false;

            return loadingState;
        }, {})
    );

actual state
    useEffect(() => {
        console.log('actual loading state', loadingState);
    }, [Object.keys(loadingState).map(id => id)]);

handleSelect function
    const onSelect = useCallback(
        async (id: string) => {
            const selectedServicesIds = selectedServices.map(service => service.id);
            setAddingInProgress(true);
            console.log('set to true', loadingState);
            setLoadingState({ ...loadingState, ...{ [id]: true } });
            // set to true {0: false, 1: false}
            // actual loading state {0: true, 1: false}
            // click on second service
            // set to true {0: false, 1: false}
            // actual loading state {0: false, 1: true} <-- there is need to be {0: true, 1: true}

            if (selectedServicesIds.includes(id)) {
                selectedServicesIds.splice(selectedServicesIds.findIndex(serviceId => serviceId === id), 1);
                await updateServices(selectedServicesIds);
            } else {
                selectedServicesIds.push(id);
                await updateServices(selectedServicesIds);
            }
            setAddingInProgress(false);
            console.log('set to false', loadingState);
            setLoadingState({ ...loadingState, ...{ [id]: false } });
        },
        [selectedServices]
    );

Comment: What is the question?
Answer: I think this will work
    const onSelect = useCallback(
        async (id: string) => {
            const selectedServicesIds = selectedServices.map(service => service.id);
            setAddingInProgress(true);
            console.log('set to true', loadingState);
            setLoadingState(prev => ({ ...prev, ...{ [id]: true } }));
            // set to true {0: false, 1: false}
            // actual loading state {0: true, 1: false}
            // click on second service
            // set to true {0: false, 1: false}
            // actual loading state {0: false, 1: true} <-- there is need to be {0: true, 1: true}

            if (selectedServicesIds.includes(id)) {
                selectedServicesIds.splice(selectedServicesIds.findIndex(serviceId => serviceId === id), 1);
                await updateServices(selectedServicesIds);
            } else {
                selectedServicesIds.push(id);
                await updateServices(selectedServicesIds);
            }
            setAddingInProgress(false);
            console.log('set to false', loadingState);
            setLoadingState(prev => ({ ...prev, ...{ [id]: false } }));
        },
        [selectedServices]
    );

Comment: Thanks! Didn't know that setState can receive callback with previous state.
Answer: Since there is no question to answer I will just review real quick:

Your map in [Object.keys(loadingState).map(id => id)] always creates a new object so your effect will be performed on each render which is not desireable
Your callback returns a promise, which should work but its not normal to assing async handlers


Navegação entre telas (JavaFX)

Question: Tenho um programa de agenda e na tela principal tenho a opção de Adicionar Contato. Quando ele é clicado é aberta uma nova tela para que se possa inserir os dados. Quando o botão Salvar dessa segunda tela é ativado, ele salva os dados corretamente e fecha esse segundo stage. Porém, a lista de clientes da tela principal não é atualizada automaticamente quando isso acontece, eu preciso clicar em um botão Atualizar. Como eu faço pra chamar o metodo atualizar dessa primeira tela e atualizá-la através da segunda?
Comment: Poderia colocar trechos do código para que o pessoal possa ajudar melhor?
Answer: Quando você for criar o segundo stage, defina o método setOnCloseRequest, como abaixo, colocando um método que carrega os dados na tabela de contatos. Quando o segundo stage for encerrado será chamado esse método.
<code>segundoStage.setOnCloseRequest(event  -> {
    carregarDadosTabela();
});
</code>

Navegação entre telas (JavaFX)


Onclick não funciona no Firefox e IE

Question: Esta função não funciona no firefox e no IE:
No javascript:
function scrollTo() {
   var _offset = 90;
   $('html, body').animate({ scrollTop: $('#videoItem').offset().top - _offset }, 'slow');
   return false;
 }

No HTML:

Alguém pode me ajudar? Obrigado.
Comment: Mude o nome da função, esso nome é de outro metodo nativo de JS. http://www.w3schools.com/jsref/met_win_scrollto.asp. E veja se resulta
Comment: Obrigado, funcionou! Só que no Chrome a tela dá uma piscada, sabe me dizer porque?
Comment: Acho que pode ser algum callback, verifica que outras funções está sendo executado
Answer: Você nomeou a função com o mesmo nome que uma função nativa do Javascript. Renomeie a função que passará a funcionar. Veja o site da MDN

Onclick não funciona no Firefox e IE


Obrigar a preencher checkbox sempre que registar determinada tarefa

Question: Tenho o seguinte formulário para registar as tarefas. Registo as tarefas separadamente.
Código:

Comeu Bem:
 Sim
<input type="checkbox" name="Notas" id="Notas11" Value="Sim" required />
 Não
<input type="checkbox" name="Notas" id="Notas12" Value="Não" required />

<input type="hidden" id="tarefa18" name="tarefa" value="30">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo18();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Pequeno Almoço</button><button type="button" name="abrir18"></button>

<textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>

Ajax para inserir:
function inserir_registo18()
{

    var dadosajax = {
        'tarefa' : $("#tarefa18").val(),
        'Notas' : $("#Notas11").val(),
        'Notas' : $("#Notas12").val(),
        'Observacao' : $("#Observacao18").val()
    };
    $.ajax({
        url: './insertarefa1',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        {
        }
    });
}

Pretendo que sempre que executa esta ação onclick="inserir_registo18();if(confirm('Pretende registar esta atividade?')) this.disabled=true;" do botão para registar, que verifique se uma das checkboxes está preenchida, caso não esteja preenchida, não execute a ação e obrigue a preencher uma das checkboxes.
Estava a tentar:
function inserir_registo18()
    {
        var checado = $("#Notas11").is(':checked')
        var checado1 = $("#Notas12").is(':checked')
        if(checado == true || checado1 == true){
        var dadosajax = {
            'tarefa' : $("#tarefa18").val(),
            'Notas' : $("#Notas11").val(),
            'Notas' : $("#Notas12").val(),
            'Observacao' : $("#Observacao18").val()
        };
        $.ajax({
            url: './insertarefa1',
            type: 'POST',
            cache: false,
            data: dadosajax,
            error: function(){

            },
            success: function(result)
            {
            }
        });
       }
    }

Edição de pergunta:
Exemplo:

Comeu Bem:
 Sim
<input type="checkbox" name="Notas" id="Notas11" Value="Sim" required />
 Não
<input type="checkbox" name="Notas" id="Notas12" Value="Não" required />

<input type="hidden" id="tarefa18" name="tarefa" value="30">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo18();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Pequeno Almoço</button><button type="button" name="abrir18"></button>

<textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>

Comeu Bem:
 Sim
<input type="checkbox" name="Notas" id="Notas" Value="Sim" required />
 Não
<input type="checkbox" name="Notas" id="Notas1" Value="Não" required />

<input type="hidden" id="tarefa19" name="tarefa" value="31">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo19();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Almoço</button><button type="button" name="abrir19"></button>

<textarea id="Observacao19" name="Observacao" style="color: black;"></textarea>

Comeu Bem:
 Sim
<input type="checkbox" name="Notas" id="Notas2" Value="Sim" required />
 Não
<input type="checkbox" name="Notas" id="Notas3" Value="Não" required />

<input type="hidden" id="tarefa20" name="tarefa" value="32">
<button class="btn btn-info btn-sm botao" onclick="inserir_registo20();if(confirm('Pretende registar esta atividade?')) this.disabled=true;">Lanche</button><button type="button" name="abrir20"></button>

<textarea id="Observacao20" name="Observacao" style="color: black;"></textarea>

javascript:
function inserir_registo18()
{
    var checado = $("#Notas11").is(':checked')
    var checado1 = $("#Notas12").is(':checked')
    var nome = $("#IniciarTarefa").val();

    if(nome == ""){
        alert("Tem de Iniciar a tarefa!");
   }else{
    if(checado == true || checado1 == true){
    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa' : $("#IniciarTarefa").val(),
        'Colaborador' : $("#Colaborador").val(),
        'tarefa' : $("#tarefa18").val(),
        'Notas11' : $("#Notas11").is(":checked") ? $("#Notas11").val() : '',
        'Notas12' : $("#Notas12").is(":checked") ? $("#Notas12").val() : '',
        'check' : $("#check").is(":checked") ? $("#check").val() : '',
        'Acompnhante' : $("#Acompnhante").val(),
        'Observacao' : $("#Observacao18").val()
    };
    $.ajax({
        url: './insertarefa4',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        {
        $('#check').prop('checked', false).val("Sim");
        $("#Acompnhante").val("").hide();
        }
    });
}else {
      alert('Selecione um campo');
    }

}
}
function inserir_registo19()
{
    var checado = $("#Notas").is(':checked')
    var checado1 = $("#Notas1").is(':checked')
    var nome = $("#IniciarTarefa").val();

    if(nome == ""){
        alert("Tem de Iniciar a tarefa!");
   }else{
    if(checado == true || checado1 == true){
    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa' : $("#IniciarTarefa").val(),
        'Colaborador' : $("#Colaborador").val(),
        'tarefa' : $("#tarefa19").val(),
        'Notas' : $("#Notas").is(":checked") ? $("#Notas").val() : '',
        'Notas1' : $("#Notas1").is(":checked") ? $("#Notas1").val() : '',
        'check' : $("#check").is(":checked") ? $("#check").val() : '',
        'Acompnhante' : $("#Acompnhante").val(),
        'Observacao' : $("#Observacao19").val()
    };
    $.ajax({
        url: './insertarefa5',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        {
        $('#check').prop('checked', false).val("Sim");
        $("#Acompnhante").val("").hide();
        }
    });
    }else {
      alert('Selecione um campo');
    }
}
}
function inserir_registo20()
{
    var checado = $("#Notas2").is(':checked')
    var checado1 = $("#Notas3").is(':checked')
    var nome = $("#IniciarTarefa").val();

    if(nome == ""){
        alert("Tem de Iniciar a tarefa!");
   }else{
    if(checado == true || checado1 == true){
    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa' : $("#IniciarTarefa").val(),
        'Colaborador' : $("#Colaborador").val(),
        'tarefa' : $("#tarefa20").val(),
        'Notas2' : $("#Notas2").is(":checked") ? $("#Notas2").val() : '',
        'Notas3' : $("#Notas3").is(":checked") ? $("#Notas3").val() : '',
        'check' : $("#check").is(":checked") ? $("#check").val() : '',
        'Acompnhante' : $("#Acompnhante").val(),
        'Observacao' : $("#Observacao20").val()
    };
    $.ajax({
        url: './insertarefa6',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        {
        $('#check').prop('checked', false).val("Sim");
        $("#Acompnhante").val("").hide();
        }
    });
    }else {
      alert('Selecione um campo');
    }
}
}

Comment: Qual o erro que está dando amigo?
Comment: Está tentando com um id que não existe...
Comment: @Maycon F. Castro, não está a dar erro, e não regista na base de dados, mas o utilizador fica com a ideia que fez o registo na base de dados, e não devia finalizar o processo de bloqueio do botão até a checkbox estar preenchida
Comment: @Darlei Fernando Zillmer já alterei os ids, assim não regista, mas pretendia que ao clicar no botão para inserir, se verificasse que nenhuma das checkboxes não estivesse preenchida, mostrasse um alerta para preencher e só depois de preencher terminasse a ação do botão inserir
Comment: Possível duplicata de [Checkbox retorna sempre false quando faço .is(":checked");](https://pt.stackoverflow.com/questions/38957/checkbox-retorna-sempre-false-quando-fa%c3%a7o-ischecked)
Comment: @Darlei Fernando Zillmer, não é duplicada a pergunta, o meu problema é diferente. Vou explicar: Quando faço para inserir na base de dados, se o processo for concluído, desativa o botão para inserir aquela tarefa, e o que pretendo é que se verificar que nenhuma checkbox está preenchida, não termine o processo do botão ao ponto de o desativar, para poder inserir a tarefa
Answer: Tente a seguinte maneira:

function inserir_registo18() {
  var dadosajax = {
    'tarefa': $("#tarefa18").val(),
    'Notas': $("#Notas11").val(),
    'Notas': $("#Notas12").val(),
    'Observacao': $("#Observacao18").val()
  };
  $.ajax({
    url: './insertarefa1',
    type: 'POST',
    cache: false,
    data: dadosajax,
    error: function() {

    },
    success: function(result) {}
  });
}
$(document).on('click', '.botao', function(e) {
  e.preventDefault();
  if (confirm('Pretende registar esta atividade?')) {
    if ($("#Notas11").is(':checked') || $("#Notas12").is(':checked')) {
      alert('Inserindo');
      inserir_registo18();
    } else {
      alert('Selecione um campo');
    }
  }
})

    Comeu Bem:
     Sim
    <input type="checkbox" name="Notas" id="Notas11" Value="Sim" required />
     Não
    <input type="checkbox" name="Notas" id="Notas12" Value="Não" required />

  <input type="hidden" id="tarefa18" name="tarefa" value="30">
  <button class="btn btn-info btn-sm botao">Pequeno Almoço</button><button type="button" name="abrir18"></button>

    <textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>

Answer: Olhando seu código percebi algumas coisas:
<input type="checkbox" name="Notas" id="Notas11" Value="Sim" required/>
<input type="checkbox" name="Notas" id="Notas12" Value="Não" required/>

Esses input tem o mesmo name="Notas" e eles são do type="checkbox".

Se apenas um desses inputs pode ser selecionado por vez o melhor tipo para eles seria o type="radio"
Se os dois podem ser marcados ao mesmo tempo você mantem o type="checkbox", porem o ideal é você não colocar o name="Notas" igual para os dois

Agora olhe essas keys em seu objeto:
var dadosajax = {
    'tarefa' : $("#tarefa18").val(),

/// ; ↓
    'Notas' : $("#Notas11").val(),
    'Notas' : $("#Notas12").val(),
/// ; ↑ Essa aqui esta sobrescrevendo a primeira

    'Observacao' : $("#Observacao18").val()
};

Como as duas entradas tem a mesma key(Notas), a ultima sera mantida, veja o exemplo abaixo:

let obj = {
    'Notas': 11111,
    'Notas': 22222,
};
console.log( obj );

Corrigindo e fazendo a checagem
Primeiro passo vou alterar seus input para o type='radio', pois como eles representam Sim e Não acredito que você queira que o usuário escolha entre um ou o outro. Outro problema nesses input é que a label deles não esta com atributo for correto, esse atributo deve indicar o id do elemento alvo. Veja abaixo como ficou após a alteração:
 Sim
<input type="radio" name="Notas" id="Notas11" Value="Sim" required/>

 Não
<input type="radio" name="Notas" id="Notas12" Value="Não" required/>

Segundo passo vamos fazer a checagem.
Como você já esta usando o jQuery e o seu input agora é um input[type='radio'], ou seja, somente 1 pode esta checked, sua checagem pode utilizar o selector :checked e ficar +/- assim:
let elementoChecked = $('input[name="Notas"]:checked');
/// ; Busca:               ↑     ↑              ↑
/// ; Elemento com a tag `input` |              |
/// ; Com o attributo `name` igual a `Notas`    |
/// ;                             Que esteja marcado (checked)

if( elementoChecked.length == 0 )
{
    /// ; Se entrar aqui nenhum elemento esta marcado (checked)
}

Terceiro passo, vou retirar esse codigo if(confirm('Pretende registar esta atividade?')) this.disabled=true; do onclick e colocar ele dentro da sua função inserir_registo18 e no onclick vou fazer a chamada para a função inserir_registo18 passando como parâmetro this que naquele momento é o próprio botão, o botão vai ficar assim
<button class="btn btn-info btn-sm botao" onclick="inserir_registo18(this);">Pequeno Almoço</button>

Quarto passo, como você agora você já sabe que elemento esta checked, basta pegar o .val() deste elemento para colocar em seu objeto dadosajax e como sua função agora recebe como parâmetro o button que foi clicado você pode desativar ele dentro dela, seu código deve ficar +/- assim:

function inserir_registo18( botao )
{
    let elementoChecked = $('input[name="Notas"]:checked');
    /// ; Busca:               ↑     ↑              ↑
    /// ; Elemento com a tag `input` |              |
    /// ; Com o attributo `name` igual a `Notas`    |
    /// ;                             Que esteja marcado (checked)

    if( elementoChecked.length == 0 )
    {
        /// ; Se entrar aqui nenhum elemento esta marcado (checked)
        alert('Você precisa escolher um valor');
        return false;
    }

    var dadosajax = {
        'tarefa' : $("#tarefa18").val(),
        'Notas' : elementoChecked.val(),
        'Observacao' : $("#Observacao18").val()
    };

    console.log('dadosajax:' , dadosajax);

    /// ; Desativar botão
    if(confirm('Pretende registar esta atividade?'))
        botao.disabled=true;

    $.ajax({
        url: './insertarefa1',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(result)
        {
        }
    });
}

        Comeu Bem:
         Sim
        <input type="radio" name="Notas" id="Notas11" Value="Sim" required />
         Não
        <input type="radio" name="Notas" id="Notas12" Value="Não" required />

    <input type="hidden" id="tarefa18" name="tarefa" value="30">
    <button class="btn btn-info btn-sm botao" onclick="inserir_registo18(this);">Pequeno Almoço</button>
    <button type="button" name="abrir18"></button>

        <textarea id="Observacao18" name="Observacao" style="color: black;"></textarea>

Referencias: label, jQuery :checked Selector
Comment: mas existe um problema,  tenho várias tarefas que tenho de colocar a confirmação de sim e não, ``, se usar radio não posso usar o mesmo nome em cada uma delas e tenho de criar várias colunas na base de dados e pretendo que registe sempre na mesma coluna. Por esse motivo não posso usar radio e o checkbox desta forma permite-me fazer o registo sempre na mesma coluna.
Comment: @bruno, Acho que vale apena você editar a pegunta e: **Colocar mais dessas confirmações** , **Se possível explicar como você esta gerando esse HTML com essas confirmações.** Ex: Se elas são geradas por programação com uma certa linguagem (PHP,JavaScript,...), colocar o código que esta gerando.
Comment: editei a pergunta com o código de três exemplos tudo na mesma página.


form_set_error highlights only select fields and not other required field types

Question: I have a content type with few required fields. When I try to save a node without filling any data, all the required fields throw an error message saying the field is required, but the required fields aren't highlighted in red. Only the select fields are highlighted; date fields or text fields aren't.

This is happening when I use the Zero Point theme (version 7.x-4.10).
How should I proceed with troubleshooting?
Comment: Hi @kiamlaluno, please let me know if you need more information.
Comment: Hi, any suggestions/ tips on this please?
Answer: This was because of CSS overwritten by Zero Point theme, added more classes in my custom CSS file:
<code>    /* .form-item input.error, */
    .form-wrapper .fieldset-wrapper .form-item input.error,
    .form-item textarea.error,
    .form-item select.error {
            border: 2px solid red;
    }
</code>


Find element in list n times Python

Question: Given are
a = [1, 4, 2, 5]

b = [[[0, 1]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 6]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 4]],
     [[0, 5]], [[0, 6]], [[0, 4]], [[0, 2]], [[0, 2]], [[0, 4]], [[0, 4]], [[0, 5]], [[0, 5]], [[0, 5]], [[0, 1]],
     [[0, 5]], [[0, 1]], [[0, 1]]]

My goal is to iterate over the list a and to identify (print) those elements in b which have the element of a as element at index 1. The whole thing becomes difficult by the fact that this process may occur exactly three times for each element. After that, the next index in a is to be selected.
In concrete terms, the whole thing should look like this at the end:
[[0, 1]]
[[0, 1]]
[[0, 1]]
[[0, 4]]
[[0, 4]]
[[0, 4]]
[[0, 2]]
[[0, 2]]
[[0, 2]]
[[0, 5]]
[[0, 5]]
[[0, 5]]

All elements in b beyond that are to be ignored, even and especially if they occur more than three times.
I have already tried various techniques ( random, while loop, etc.), racked my brain and searched this forum, but I am stuck.
It doesn't matter which elements are selected in b, the main thing is that there are three for each element in a.
Comment: What should happen for elements with more than three repeats (like `[[0,1]]`) ? Or fewer ? And what have you tried so far ?
Comment: Could exits elements in b like: b = [[[0, 1], [0, 5]], [[0, 2]], ...]?
Comment: I don't know what is so heavy to understand in my question. I wrote everything down.
Comment: You have however not provided any code. StackOverflow is a [questions and answers
site](https://stackoverflow.com/about), not a code-writing service. Please read
through [How to Ask](https://stackoverflow.com/help/how-to-ask) and [edit] your
question to reflect your work.
Comment: @ljmc I also realize that stackoverflow is not a code writing service. I had simply hoped to convey a concept, nothing more.
Answer: This will count and filter your b input on a values using a Counter to count the values and appending to the filtered list only is the value count is less than 3.
from collections import Counter

a = [1, 4, 2, 5]

b = [
    [[0, 1]],
    [[0, 2]],
    [[0, 3]],
    [[0, 4]],
    [[0, 5]],
    [[0, 6]],
    [[0, 2]],
    [[0, 3]],
    [[0, 4]],
    [[0, 5]],
    [[0, 4]],
    [[0, 5]],
    [[0, 6]],
    [[0, 4]],
    [[0, 2]],
    [[0, 2]],
    [[0, 4]],
    [[0, 4]],
    [[0, 5]],
    [[0, 5]],
    [[0, 5]],
    [[0, 1]],
    [[0, 5]],
    [[0, 1]],
    [[0, 1]],
]

c = Counter()

b_filtered = []

b.sort(key=lambda x: x[0][-1])

for x in b:
    v = x[0][-1]
    if v in a and c[v] < 3:
        b_filtered.append(x)
    c[v] += 1

b_filtered contains
[[[0, 1]],
 [[0, 1]],
 [[0, 1]],
 [[0, 2]],
 [[0, 2]],
 [[0, 2]],
 [[0, 4]],
 [[0, 4]],
 [[0, 4]],
 [[0, 5]],
 [[0, 5]],
 [[0, 5]]]

Comment: The code does what I asked for, however I am not experienced enough to understand everything yet. I have not yet dealt with lambda enough. Thanks anyway and no hard feelings.
Comment: No hard feelings, and this lambda simply tells `sort` how to access the value on which it should sort `b` so that you only need to count values out later.
Answer: If you want to make it easier, you can simply follow the steps below:
a = [1, 4, 2, 5]

b = [[[0, 1]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 6]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 4]],
     [[0, 5]], [[0, 6]], [[0, 4]], [[0, 2]], [[0, 2]], [[0, 4]], [[0, 4]], [[0, 5]], [[0, 5]], [[0, 5]], [[0, 1]],
     [[0, 5]], [[0, 1]], [[0, 1]]]

for val_a in a:
    counter = 0
    for val_b in b:
       if val_a == val_b[0][1]:
           counter += 1
           if counter < 4:
                print(val_b)

I hope I could help! :D
Answer: You may follow these steps to achieve your desired output
a = [1, 4, 2, 5]
b = [[[0, 1]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 6]], [[0, 2]], [[0, 3]], [[0, 4]], [[0, 5]], [[0, 4]],
     [[0, 5]], [[0, 6]], [[0, 4]], [[0, 2]], [[0, 2]], [[0, 4]], [[0, 4]], [[0, 5]], [[0, 5]], [[0, 5]], [[0, 1]],
     [[0, 5]], [[0, 1]], [[0, 1]]]

result = []
count = {}
for i in a:
    for j in b:
        if j[0][1] == i:
            if i not in count:
                count[i] = 1
                result.append(j)
            elif count[i] < 3:
                count[i] += 1
                result.append(j)

for i in result:
    print(i)

Comment: if j[0][1] == I: gives me an error. Not subscriptable.

Find element in list n times Python


Does it make sense to take the grad of this?

Question: I have been asked to calculate the grad of a function $V(r)$, where $r$ is a position vector and $\omega$ is the angular velocity. But surely, $V(r)$ is a scalar? So how is this possible? Context: I want to show that a force is conservative with this potential, the force is $F=-m\omega\land(\omega\land r)$
$$V(r)=-\frac12 m |\omega \land r|^2 $$
Answer: The gradient operator transforms a scalar field $\Phi(\vec t)$ into the vector field $\nabla \Phi(\vec r)$.  It is written in Cartesian Coordinates as
$$\nabla \Phi(\vec r)=\hat x\frac{\partial \Phi(\vec r)}{\partial x}+\hat y\frac{\partial \Phi(\vec r)}{\partial y}+\hat z\frac{\partial \Phi(\vec r)}{\partial z}$$
Let $V(\vec r)=-\frac12m|\vec \omega \times\vec r|^2$.  Then, we can write $V(\vec r)$ as
$$\begin{align}
V(\vec r)&=-\frac m2 (\vec \omega \times \vec r)\cdot (\vec \omega \times \vec r)\\\\
&=-\frac m2 \vec \omega \cdot (\vec r\times (\vec \omega \times \vec r))\\\\
&=-\frac m2\omega \cdot(r^2\vec \omega-(\vec r\cdot \vec\omega)\vec r)\\\\
&=\frac m2((\vec \omega\cdot \vec r)^2-\omega^2r^2)
\end{align}$$
Then, the gradient of $V$ is given by
$$\begin{align}
\nabla V(\vec r)&=\frac m2 \left(2(\vec \omega \cdot \vec r)\nabla (\vec \omega \cdot \vec r)-2r\omega^2\nabla (r)\right)\\\\
&m\left((\vec \omega \cdot \vec r)\vec \omega-\omega^2\vec r\right)\\\\
&=m(\vec\omega\times(\vec \omega\times\vec r))
\end{align}$$


Are multiple domain can improve images loading speed

Question: I read this article Optimize Parallel Downloads to Minimize Object Overhead and write a test demo
But the result is not I expected,look at the waterfall figure multiple domain's images indeed parallel download but the total time no less.
Who can tell me why,thanks
multiple domain image download

single domain image download
Answer: What I think the problem with your test is that the network latency is so low (assuming its a local server), that your network performance isn't even playing a huge role here.  If you look at the time difference between those images it doesn't' even register in HTTPWatch. So the browser may be spending more time parsing, processing and rendering the downloads than it does actually downloading (just a guess).
I would hit this test site with something that will show off latency more.  If these sites are reachable on the internet, you can just use http://www.webpagetest.org/ and hit them from around the world...
~Sniff
P.S. Check out Amdahl's law, it may have a little bearing here here ;-).


What Plugin goes "type" of a FieldStorageConfig type?

Question: I have a module creating a field type. It works.  I can create and add the field through the admin UI.  However, I am trying to update a content type with hook_update_N and change a field from entity reference to my field type. I am creating the FieldConfig and FieldStorageConfig like this
$field_storage = FieldStorageConfig::create([
       'field_name' => 'content_category',
       'entity_type' => 'node',
       'type' => 'my_field_type',
    ]);

$field = FieldConfig::create([
      'field_storage' => $field_storage,
      'field_name' => 'content_category',
      'bundle' => 'story',
      'label' => $label,
      'settings' => array('display_summary' => TRUE),
      'entity_type' => 'node',
    ]);
    $field->save();

This results in an error that says
The "my_field_type" plugin does not exist

but i can  create a field of type "my_field_type" and when I export configurations for my field created through the UI  the type says "my_field_type"
So What plugin is it looking for in the "type" field of a fieldConfigStorage?  In my Plugin folder of my module the Formatter.php  Field.php and Widget.php  which of these is the correct one?
Answer: My Bug was actually in
entitity_get_form_display()->setComponent('field', array(
type=>my_field_type))

it should have been
entitity_get_form_display()->setComponent('field', array(
type=>my_field_type_widget))


emailing users in user reference field with rules

Question: I am working on a site for an academic conference. Right now, we have two content types (1) proposal and (2) peer review. In the proposal content type, an author can add multiple presenters to a user reference field. When the node is saved, I have a rule that loops through the user reference field and sends an email notification to all the presenters that the proposal has been submitted. Works great!
Now the question. I want to send an email to that same group of users when someone else posts a peer review. I have figured out how to notify the "author" of the proposal but I want to notify all the users listed in the node reference field.
Right now my rule is set up as follows:
Event: after saving new content
Conditions: content is of type > peer review
Actions: Fetch entity by property:
-Value: node
-Value: node reference
-Data selector: node
Variable label: Fetched proposal
Variable name: fetched_proposal
Then I have a loop:
Data selector: fetched-proposal
Current list item
Variable label: Current proposal item
Variable name: proposal_list_item
Then I have an action to send the mail. Since I've looped over the proposal connected to the peer review, I have available a token for the presenter field which contains the node reference. I've used that token in the "To" value field.
I think this should work but I don't get emails when testing.
When I check my log messages I see this error: The loop Loop () fails the integrity check and cannot be executed. Error: Data selector fetched-proposal: for parameter list is invalid.
Can anyone help me figure this out?
Answer: I think you are fetching the user reference wrongly. You should try this:

On the Action:Fetch Entity by ID
Value:User
Data selector :node:field-name:uid (this is your user reference field
Variable label:Fetched entity
Variable name :user_entity

Then you are good to go!


Converter imagem para CSS

Question: É possível converter a imagem abaixo em css puro?

Se sim, como eu poderia fazer isso? Alguém tem um exemplo?
Preciso também que tenha aquela divisão, exatamente como na imagem.
Comment: Quando vc diz "Preciso também que tenha aquela divisão" o que exatamente vc quer dizer?
Comment: Wendler da para fazer apenas um uma div sim! Olha a edição que eu fiz na minha resposta que vc vai ver como ficou!
Comment: @hugocsl Show de bola, só me da mais uma dica. Como que eu poderia fazer para colocar mais dois números ali, um em cada retângulo, tudo na mesma DIV. Tentei fazer separando classes, mas deu problema por que o segundo retângulo usa o position:absolute, então cobre o texto.
Comment: Fiz com a seguinte classe: `.counter{color:#fff;font-family:Tahoma;font-size:60px;font-weight:700;letter-spacing:12px;line-height:63px;padding:0 0 0 6px;height:70px;margin-top:-1px;position:relative;width:105px}`

Deu certo no primeiro retângulo, mas no segundo não apareceu.
Comment: Wendler não precisa disso. Veja a edição que eu fiz no meu código, que vc vai entender. Já coloquei um número dentro de cada Div, não precisa usar position nem nada. Se a resposta resolveu o seu problema considere marca-la come resolvida `✔` assim mantemos os site organizado.
Comment: @hugocsl Na verdade já tinha tentando algo assim, problema é que naõ vai funcionar, pois o sistema gera os dois números dentro da div, não tem como eu separar eles.
Comment: Esses números são alterados sempre, é um cronometro regressivo.
Comment: Outra coisa, eu preciso que seja com a classe **counter**, exatamente com esse nome, pois o sistema busca informação através dessa classe.
Comment: O que vc quer já é uma pergunta diferente. Se vc tiver alguma outra dúvida crie uma pergunta nova. Essa eu já respondi, se quer uma coisa diferente do que pediu crie outra pergunta pq essa já está ficando bastante bagunçada e fora do escopo do que foi pedido. **marca essa** e abre outra pergunta que facilita.
Comment: Perfeito, fiz uma nova pergunta: https://pt.stackoverflow.com/questions/282706/problema-com-atr%C3%ADbuto-position-css
Answer: É possível, sim! E eu diria que até simples.
Basta você desmembrar os elementos da figura para encontrar a solução completa.
Você poderia começar com:

E criar os estilos, primeiro o retângulo:
 .retangulo {
display: block;
width: 50px;
height: 80px;
background-color: #0000ff;
border-radius: 10px;
}

Agora precisamos criar essa "luz" que sombreia a forma.
Alteramos o HTML para alocar o novo elemento:

E CSS da sombra eu fiz assim, não tá exatamente igual ao original, mas fui só montando rapidinho:
.shade {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50px;
  left: -30px;
  top: -30px;
  background: radial-gradient(rgba(255,255,255,0), rgba(255,255,255,1));
  opacity: 0.3;
  overflow: hidden;
}

Ajuste o CSS conforme as suas necessidades!
Depois é só fazer o HTML pra ficar exatamente igual na imagem de referência.
Exemplo:

.retangulo {
  display: block;
  width: 50px;
  height: 80px;
  background-color: #0000ff;
  border-radius: 10px;
}

.shade {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50px;
  left: -30px;
  top: -30px;
  background: radial-gradient(rgba(255,255,255,0), rgba(255,255,255,1));
  opacity: 0.3;
  overflow: hidden;
}

Comment: @Caique Romero Perfeito, o problema é que preciso fique os dois retângulos em uma div só, não em duas. Seria possível?
Answer: EDIT: (apena uma
) Da para fazer apenas com uma div sim, seguindo o mesmo princípio do usando o elemento ::before e colocando o backgrounde radial-gradient em cada um deles.

OBS: Para colocar o número dentro basta colocar 1 dentro da
 e o outro dentro co contente:"" do ::after

Veja o exemplo com só uma div

html, body {
    width: 100%;
    height: 100%;
    margin: 20px;
    padding: 0;
}

.retangulo {
    display: block;
    width: 50px;
    height: 80px;
    background-color: #0000ff;
    background-image: radial-gradient(circle at top left, blue 0%,rgba(255,255,255,0.5) 60%, blue 61%);
    background-repeat: no-repeat;
    background-size: 150% 80%;
    background-position: top -10px left 0;
    border-radius: 5px;
    position: relative;
    box-shadow: 0 0 10px rgba(0,0,0,0.65) inset;
    font-size: 32px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-weight: bold;
    color: aliceblue;
    text-align: center;
    line-height: 80px;

}
.retangulo::before {
    content: "2";
    display: block;
    width: 50px;
    height: 80px;
    background-color: #0000ff;
    background-image: radial-gradient(circle at top left, blue 0%,rgba(255,255,255,0.5) 60%, blue 61%);
    background-repeat: no-repeat;
    background-size: 150% 80%;
    background-position: top -10px left 0;
    border-radius: 5px;
    position: absolute;
    left: 51px;
    box-shadow: 0 0 10px rgba(0,0,0,0.65) inset;
}

1

Da para fazer sim meu jovem, olha o resultado ai. Puro CSS!
Usei um box-shadow com inset para fazer o sombreamento escuro na parte de dentro, e um pseudo elemento ::after para fazer o "brilho" com um background radial gradiente

html, body {
    width: 100%;
    height: 100%;
    margin: 20px;
    padding: 0;
}
.btn {
    width: 60px;
    height: 80px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.75) inset;
    background-color: blue;
    border-radius: 6px;
    overflow: hidden;
    position: relative;
    float: left;
    margin-right: 2px;
}
.btn::after {
    content: "";
    border-radius: 50%;
    position: absolute;
    top: -70px;
    left: -50px;
    width: 120px;
    height: 120px;
    background-image: radial-gradient(blue 30%, azure);
    opacity: 0.65;
}

Comment: Perfeito, o problema é que preciso fique tudo em uma div só, não em duas. Seria possível?
Comment: Wendler a olha a primeira parte da minha resposta com o **EDIT**, da para fazer só com uma `div` sim!

Converter imagem para CSS


Limit Proof, Absolute Value

Question: Suppose $\displaystyle \lim_{n \rightarrow \infty}$$x_n$ = $c$. Prove that $\displaystyle \lim_{n \rightarrow \infty}$ $|x_n|$ = $|c|$.
My gut tells me the triangle inequality is what I need to use, but I can't seem to reason it out.
Thanks.
Answer: Yes, use the reverse triangular inequality http://en.wikipedia.org/wiki/Triangle_inequality:
$$
||x_n|-|c||\leq |x_n-c|.
$$
And then the squeeze theorem.
Comment: By assumption, $\lim x_n=c$, ie $\lim (x_n-c)=0$ ie $\lim |x_n-c|=0$. So the rhs tends to $0$, and the lhs is bounded below by $0$. Squeeze indeed.
Comment: I'm sorry could you elaborate on how the squeeze theorem might follow from here?
Comment: oh, great thanks, i think I follow you now
Comment: ah yes, fully clear to me now. Much appreciated!
Comment: @PaulGerard Great, then.

Limit Proof, Absolute Value


shutting down gcloud service in case of DDos attacks

Question: my company has a small and nice product on google could (using public webapp, functions and storage).
it's been hours I'm searching for a solution like a kill switch for services in case of any threat or attack on any of services. I've found that we can define max instances for each cloud function which is somehow cool and prevents too many threats.
but the main problem is the cloud storage. files on buckets are public and I don't know which solution is better to restrict download requests to bucket. one of them is that we create a new function (with max instance defined) and stream download requests from there to webapp. in this case bucket can be private. but after some cost estimations (an streaming function will be involved in each download) apeared that it may cost a lot, since the product has a map with custom tiles and webapp requests around 16 image files at once on init.
after thinking about different solution the only way I can see to prevent DDos attacks is to monitor the usage and shutdown services (specially storage service) at once to have time to track the issue and fix it.
but google cloud doesn't offer anything like this. at least I can't find it. something that brings the whole project (or part of it) to maintenance mode and rejects all requests. I can add a config for each function execution or storage download and turn it off whenever I want. but I think still google cloud counts those requests and bills my boss.
is there anybody who knows a good solution. scenarios in my mind are like:

multiple IPs try to download request files in bucket continuosly and (~200 dn/s) for hours
multiple IPs try to invoke functions but just to keep instances live and intrupt real users connections

I'm wondering if there is anyway (instead of custom way) to restrict each ip to have max 2000 requests per day.
Answer: Google has mechanisms in place to protect its cloud infrastructure and its production services. The Google cloud infrastructure itself does have an additional layer of DDoS protection which it uses to defend against large scale attacks.You can take different approaches to serve non-public content from GCS to your end-users.
One of them is using  Google Cloud Armor for DDoS defense.Google Cloud Armor is deeply connected to the Global Load Balancing infrastructure which allows it to inspect incoming traffic and recognize and dissipate incoming DDoS attacks.
To enable DDoS protection on your project, you can enable managed protection on The GCP UI, under Cloud Armor. Please refer to this documentation for more details on DDoS mitigation on Cloud Armor.
Secondly, here are some additional steps you can take to prevent denial of service attacks on cloud storage: try to isolate your internal traffic from external data, you can enable the DDoS protection by enabling the Proxy based Load Balancing, secure the deployment using network fire rules and Identity access management, protect the Google cloud storage.
I would also recommend you to have a look at the documentation on Retention policies and retention policy locks.
Also to check the feature to have restrictions on each ip to have certain requests per day, checkout this useful documentation and have a look at this blog on How Google has proven protected the layer 7 DDos attack for more information.


Discrete Fourier Transform of a shift of a tuple over a finite field

Question: Let $a = a_0 a_1 \cdots a_{N-1}$ be a sequence over a finite field $\mathbb{F}_q$, where $N \mid q^n-1$ for some $n$. Let $\xi_N$ be a primitive $N$-th root of unity in the extension $\mathbb{F}_{q^n}$. Suppose we know a Discrete Fourier Transform (DFT) of $a$, given by
$$
A_i = \sum_{j=0}^{N-1} a_j \xi_N^{ij}.
$$
Fix $u$ with $0 \leq u \leq N-1$. What is the DFT of the sequence $(a_{j+u \pmod{N}})_{j=0}^{N-1}$? That is, can we write the DFT of the shifted sequence in terms of the DFT of the original? Thank you.
Comment: Presumably $a_{j+u} = a_{j+u \bmod N}$? If so, the answer to your question: can we write... is Yes. If not, the $u$ new elements $a_N, a_{N+1},\cdots, a_{N-1+u}$ need to be defined, and no simple relation exists.
Comment: I'm very sorry for the late reply. I had completely forgotten about this due to some other complications. Yes, $a_{j+u} = a_{j + u \pmod{N}}$ as you guessed. I'll make the edit now. Would you please let me know what is the expression for the shifted DFT in terms of the original one? Thanks a lot.
Answer: Given that we know a Discrete Fourier Transform (DFT) of $a$, given by
$$
A_i = \sum_{j=0}^{N-1} a_j \xi_N^{ij}.
$$
and we fix $u$ with $0 \leq u \leq N-1$,  the DFT of the sequence $(a_{j+u \pmod{N}})_{j=0}^{N-1}$ is
$$
B_i = \sum_{j=0}^{N-1} a_{j+u} \xi_N^{ij}=\sum_{k=0}^{N-1} a_{k} \xi_N^{i(k-u)}=\xi_N^{-iu} \sum_{k=0}^{N-1} a_{k} \xi_N^{ik},
$$
which gives
$$
B_i = \xi_N^{-iu} A_i,\quad 0\leq i\leq N-1.
$$


What limits are imposed for mysql user creation?

Question: MySQL 5.1.x
What is the cost of an account on disk when it is created in MySql? Also, what is the max number of accounts you can create?
Answer: What is the cost of an account on disk when it is created in MySql?
Practically nothing (a few K to create the rows in the Grant tables).
what is the max number of accounts you can create?
Practically unlimited (the Grant tables can't exceed the maximum number of rows in a table, for which there is no upper limit in modern InnoDB tables, but for obscenely large numbers of rows you may have performance problems.  The chance of you having that many users / GRANTs is so small as to be a non-factor in capacity planning).
Answer: MySQL accounts are stored in the user table of the mysql database. You are only limited by the amount of drive space you have. The disk cost is equal to the size of the row.


A number Doubles When Last Digit Moves To The First Digit: Fermats Little theorem usage.

Question: My addition to the solution from here https://www.youtube.com/watch?v=1lHDCAIsyb8
goes whith usage of Fermats little theorem, but i want ask, if it is used properly there, because i have some doubts. But if it is correct, the solution is really short and elegant.
So the task is to find the least positive number, what doubles, if you move the least digit - the right digit  to the first - on very left position.
So let

a be the first digit in [1..9]
b the rest
m - amount of digits after the first one

$$  \begin{cases}  x = 10 b + a \\
2 x = a *10^m + b\end{cases}  \\
20b + 2a = a *10^m  + b \\
b = \frac{2a*(5 * 10^{m-1}-1)  }{19  }$$
Since b is natural number, and a is a digit [1..9], the rest in brackets must be divisible to 19, or:
$$  5 * 10^{m-1} \text { mod }19 = 1 \\ $$
Understood now, what it looks like ?
Here, my part of the solution begins.
By the Fermat's little theorem:
$$ 10^{18} \text{ mod } 19 = 1 $$
And it is the smallest power, to get one as the modular rest.
So i rewrite it like that :
$$ 5 * 5^{m-1} * 2^{m-1} \text{ mod } 19 = 5^{18} *   2^{18}  \text{ mod } 19 = 1 $$
Here is the disputable step:
One could estimate m-1 = 18, m = 19 by counting "2" 's , is it actually a valide step?
The right solution on the video is m = 17 how to get it from here, i feel like it is possible somehow by the Fermat's little theorem.
Thanks for answers
Answer: You have
$$\begin{equation}\begin{aligned}
5 \times 10^{m-1} & \equiv 1 \pmod{19} \\
(2 \times 5) \times 10^{m-1} & \equiv 2 \pmod{19} \\
10^{m} & \equiv 2 \pmod{19} \\
10 \times 10^{m} & \equiv 2 \times 10 \pmod{19} \\
10^{m + 1} & \equiv 1 \pmod{19}
\end{aligned}\end{equation}\tag{1}\label{eq1A}$$
where I've used that $2 \times 10 \equiv 20 \equiv 1 \pmod{19}$ to get the last line. Now you can use from Fermat's little theorem that one solution is $m + 1 = 18 \implies m = 17$.
Note the smallest value of $m$ comes from the multiplicative order of $10$ modulo $19$. This value needs to divide into $19 - 1 = 18 = 2 \times 3 \times 3$. Thus, if it's anything smaller, then $m + 1$ would need to be a proper factor of $18$, i.e., $1$, $2$, $3$, $6$ or $9$. You can confirm that you get, modulo $19$, the values of $10$, $5$, $12$, $3$ and $18$, respectively, so the smallest value of $m$ is indeed $m = 17$.
Comment: wow the 20 mod 19 = 1 is realy genial... or i was blind. Thanks a lot, this make the solution short and perfect
Answer: In your last displayed line (after "I rewrite like this"), you had a $5$ on the Left Hand Side.
In fact, $$10^{17} = 2\mod 19, \cdots (\dagger)$$ and $$10^{16} = 4\mod 19, \cdots (\dagger\dagger)$$ so after multiplying by $5$, you do get that $m-1=16$.
Do you get what I mean?  I mean that $5 \times 10^{16} = 1 \mod 19$.
Fermat indeed helped shorten the calculation of $(\dagger\dagger)$.


Two halves of Java JButton (+/-)

Question: I'm sorry, but I don't even really know how to phrase this question, because I lack the terminology. Basically, I wanna know how to create this:

or this:

In Java, where multiple JButtons take up one space, with a subtle line in between them. Can anyone give me some direction, please? I've searched on my own for a while, and I can't figure it out. Thank you!
Comment: It's not a single button - It's really just multiple buttons with specific layout / borders to make them "look" different
Comment: Thanks, @Krease ! Do you have advice on how to give the JPanel that contains the two buttons a border that looks like a normal JButton?
Answer: One can create a set of buttons (or other widgets) grouped in a JToolBar. There are methods like setBorderPainted(), setFloatable(), etc., to customize the toolbar properties. Here is a basic example:
import javax.swing.*;
public class MyApp {
    public static void main(String[] args) {
        displayGui();
    }
    private static void displayGui() {
        JToolBar toolBar = new JToolBar();
        JButton saveButton = new JButton("Save");
        JButton deleteButton = new JButton("Delete");
        toolBar.add(saveButton);
        toolBar.add(deleteButton);
        JFrame frame = new JFrame("My App");
        frame.add(toolBar);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(100, 100);
        frame.setLocation(100, 100);
        frame.setVisible(true);
    }
}

EDIT:
An example toolbar (image only):
Comment: That's really creative! But I think the JToolBar causes more problems then it is worth. I like your solution, though!
Comment: Added to the answer an image of the toolbar (created using `JToolBar`) I had created few years back (as an example).
Answer: There is no direct support for what you want.
You could use a JPanel with a horizontal BoxLayout.
Then you remove the Border from each of the buttons by using setBorder(null).
You could then add a Border to the panel so it looks like the buttons share the same Border.
You can then add a JSeparator between each button.
Comment: That's very helpful! I almost have what I want. Do you have advice for how to make the JPanel's border look like a JButton's border?
Comment: You can always override the border drawing code to do whatever you need
Comment: A JButton uses a custom Border that is designed specifically for a JButton so that the state of Border can be changed when a button is clicked etc. The logic won't apply to a panel obviously. The exact Border used by the button will depend on the LAF so it will be hard to duplicate. Since you are essentially creating a custom component you should create your own custom border.

Two halves of Java JButton (+/-)


Which files and folders for version control

Question: This is just a newbie question, but what files and folders should be kept in version control software (we use mercurial, but this isn't the subject)?
I think there are those files and folders:
src/
res/
lib/
native/
override/
test/
build.xml
codenameone_settings.properties
icon.png

Do you have some other recommendation?
Answer: Your list seems to be about right. For reference this is what we use as our .gitignore file in our projects:
*.jar
nbproject/private/
build/
nbbuild/
dist/
lib/CodenameOne_SRC.zip
lib/impl/

Notice we didn't fully exclude the lib directory only its jars, zip and impl subdirectory. This means that cn1libs that we include will be under source control which isn't necessarily the best policy (since they are binary) but its convenient.
Also check out Working With A Codename One Project In Git/SVN version control
I cover the specific particulars of working with the resource file and res file hierarchy in version control in that answer.
Comment: Thanks a lot! This is what I'm looking for!


Plot the probability (success) of a binary variable from coefficients of a GLMM?

Question: I have developed a GLMM (Mixed Generalized Linear Model), as you can see in more detail [here] (Is it correct to evaluate differences of a binary variable between different places with a GLMM?)
<code> glmer(data$binary ~ data$wetland + data$predictive2 + data$predictive3 + (1|data$date), data = data, family = binomial())
</code>
, and it turns out that I want to show in a plot, the probability of success of three levels of a predictive variable (wetland). I have 4 predictive variables, all of them were significant in the model, however, I only want to plot one, for my research objective.
Considering that the model is based on several predictive variables and not just one, in addition to a random effect variable (date), is it correct to make a plot?
If the answer is yes, which one do you recommend?
Thanks for your time.
Answer: From a mixed-effects logistic regression, you can show/calculate two types of probabilities. Namely, conditional on the random effects or marginal populations. For more information on the difference between the two, check this post. Most often you want the latter.
Regarding getting this in R, you can have a look at the effects package, and the GLMMadaptive package for both fitting the model and getting the plots. An example here.


Set a block region from the block edit page

Question: I used Drupal since 4, and it always bothered me that the the block edit page doesn't include block region settings. One must return to the Blocks list to change that. It would be so much nicer if the block edit page included the region options, when using the contextual Configure links on the page.
There is no module dedicated to this on Drupal.org, so maybe there is a good reason for not doing this, like a technical limitation. Or maybe this is not useful to anyone else but me.
Is there a module for setting the block region from the block edit page? I'll create one if there isn't.
Thanks.
Answer: In Drupal 7 you have the option to set the region of the block within the block's edit page.
I haven't seen a module for this for Drupal 6 let alone earlier versions. I would strongly recommend upgrading to Drupal 7 for this feature and the plethora of other desirable features of Drupal 7 compared to it's predecessors.
I hope that helps...
Comment: Thanks for the answer, good to know it's in D7. However, upgrading is not an option.


Override FOSUserBundle login form

Question: I'm trying to override FOSUserBundle login template with my personal design. Now, I have just a problem with error messages.
If I try the default script :
{% if error %}

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

{% endif %}

I have my error message. But when I try using a div class to give some look to my error, like this :

   {% if error %}
   <button class="close" data-close="alert"></button>
   {{ error.messageKey|trans(error.messageData, 'security') }}
   {% endif %}

doesn't work I have no error message displayed in my screen. Please help, maybe its easy to resolve but I have no idea and I don't like to lose time with a simple tinks.
PS: Sorry for my english
Comment: is class  display-hide by any chance hiding the div?
Comment: yes if no error exists the div is hide
Answer: Ok I deleted display-hide class and I have my message just for the bad credentials not for empty input.

                {{ 'security.login.username'|trans }}
                <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Utilisateur" id="username" name="_username" required="required" />

                {{ 'security.login.password'|trans }}
                <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Mot de passe" id="password" name="_password" required="required" />

                <input type="submit" id="_submit" class="btn btn-success uppercase" name="_submit" value="{{ 'security.login.submit'|trans }}" />

                    <input type="checkbox" id="remember_me" name="_remember_me" value="on" />{{ 'security.login.remember_me'|trans }}

I have no message for empty input !!

Override FOSUserBundle login form


Postfix limit total sent per hour

Question: I'm not after services that could provide me with fancy fine-grained control like policyd, I don't need per user/domain control, I only want to:

limit maximim number of emails that could be sent trough Postfix mail
  system per hour, preferably but not necessary excluding domains that
  Postfix mail system itself handles.

Let's say I want to set limit of 200 messages per hour. Desired behavior is that 201 message holds until one hour period is over in order to be delivered.
I would be really amazed if solution to this could respect my previously set per-domain rate limits:
smtp_destination_concurrency_limit = 1
smtp_destination_rate_delay = 3s
smtp_extra_recipient_limit = 2

EDIT:
here are some configuration options that might be related to what I'm looking for:
anvil_rate_time_unit = 120s
smtpd_client_recipient_rate_limit = 4
smtpd_client_message_rate_limit = 4
smtpd_client_connection_count_limit = 1
smtpd_client_connection_rate_limit = 1

This configuration should limit 4 emails per 2 minutes, thus 120 per hour - but I'm not sure if it works.
Comment: @DictatorBob `smtp_destination_rate_delay` applies per domain, AFAIK.
Comment: A very crude approach would be to rate limit outgoing connections using IPtables.
Comment: Isn't this a duplicate of:
http://serverfault.com/questions/110919/postfix-throttling-for-outgoing-messages?

I also don't understand why you think that smtp_destination_rate_delay won't do what you need....
Comment: @AndréBorie Would that be feasible?
Comment: Feasible, yes. But also awful and definitely not the right tool for the job.
Comment: If you used iptables you would need to disable connection cache
Answer: You can configure Postfix to divert all messages to the hold queue, and an external script (which you'll need to write) can monitor this queue and release messages at the desired rate.
Comment: Sorry but this answer was not helpful.
Comment: @busythomas I found it helpful, at least gives a piece of the puzzle. I actually really like that, I can program any algorithm I want to manage the emails.
Answer: Postfix does not have that feature by default, you will have to use external program policyd to enforce that rule.
I believe you will find the knowledge you seek in this link:
http://ngocquyetlinux.blogspot.com/2013/05/limit-mail-with-policyd.html
Comment: Thank you, I tried policyd and unfortunately it was causing high server load. I do not recommend Policyd.

Postfix limit total sent per hour


Inner Join Laravel

Question: Estou tentando selecionar dados da tabela modulo através de relacionamento no laravel.
Onde possuo 2 tabelas Modulo e Atividades
Em atividade possuo id_modulo e preciso selecionar uma coluna chamada titulo do modulo através do id.
$status = DB::table('atividades')
            ->join('modulos', function ($join) {
                $join->on('modulos.id', '=', 'atividades.id_modulo');
            })
            ->select('modulos.*')
            ->get();
       $status = $status->titulo;

Esse script me retorna array vazio.
Comment: Existe apenas um `modulos.id` para um `atividades.id_modulo` ?
Comment: Qual versão do laravel você está usando ?
Comment: No banco realmente existem registros e estão relacionados corretamente?
Comment: Se existir mais que um registro na consulta você deve recuperar o valor por array, caso queria o primeiro registro, use `->get()[0]` ou `->first()`
Comment: @PedroHenrique versão 5.8
Comment: @KayoBruno sim o banco possui relacionamento normal entre as tabelas.
Comment: Sim, @PedroHenrique
Comment: @RichardNicson Pq não usar o Eloquent do Laravel?? O Eloquent irá lhe fornecer meios de acessar essas informações sem precisar fazer join
Answer:
Quando se usa o first(), você recupera a primeira linha da sua consulta SQL, ideal para consultas que retornará apenas um resultado.
Quando se usa o get(), você recupera todas as linhas da consulta. (Lembre-se que são necessário fazer um laço no retorno para acessar todas as linhas, mesmo que existe apena um resultado ou informar qual a posição quer recuperar).

No seu caso você está usando o get() para trazer seu resultado da consulta, como o get() retorna um array é preciso tratar antes de recuperar o valor, caso contrário receberá alguns erros, veja os exemplos abaixo.

Nesse caso o ideal seria usar o método first() que irá retornar o primeiro resultado da consulta.
$status = DB::table('atividades')
            ->join('modulos', 'modulos.id', '=', 'atividades.id_modulo')
            ->select('modulos.*')
            ->first();
$status = $status->titulo;

Caso queria continuar usando o método get(), antes de recuperar o valor de alguma coluna, deverá informar que deseja acessar a primeira posição do retorno.
$status = DB::table('atividades')
            ->join('modulos', 'modulos.id', '=', 'atividades.id_modulo')
            ->select('modulos.*')
            ->get();
$status = $status[0]->titulo;

Referência: Database: Query Builder

Inner Join Laravel


How does singing volume affect vocal range?

Question: I saw mentioned in passing in another answer:

As a rule, the more air you are forcing** through your throat, the
  higher (also louder) you can sing in a given register

I only recently noticed this myself, that higher notes sound fuller when I am "going for it" but hadn't realised this was because I was singing notes (say C4) in my chest voice when singing loudly, but head voice when singing more timidly.
How big an effect is this as a rule, and does it continue to become more significant the louder you get? Does it apply to head voice & falsetto as well as chest voice?
This is all in the context of singing higher notes, does volume also have any effect on your lower limit?
The term forcing here should be read in the physical sense NOT the musical sense i.e. straining. Air moving across/through the vocal chords makes them vibrate, if you have more air you get more volume.
At least, that's the focus of my question. Please don't get side-tracked discussing "forced singing" because that is not what I'm discussing here, but changes in volume with good technique i.e. quiet singing versus singing with power and gusto.
Comment: I wish I knew a lot more and had a lot more experience singing. With what learning I do have, I have read and confirmed for myself that to learn to sing higher notes with comfort and a clean tone, I have to relax and **not** try to force a lot of air. While "belting it out" can get you temporarily higher with projection, it seems to tire my voice more quickly and detract from my overall tone. Warming up to the higher notes with *quiet* singing seems to be the best way to expand the middle sound between my normal tone and falsetto and give me the most useful upper range extension.
Answer: Okay - so here is an answer to your edited question where you made it clear that you want to know about why you get more volume with more air and why it requires more air to hit the higher notes.
First let's talk about volume.  As you know, the vocal chords produce sound by vibrating - much the same way as a guitar string does.  Like a guitar string, the sound does not emanate entirely from the vocal chords but from all the resonators in the head and vocal tract.  A guitar string vibrates the top (soundboard) which is were most of the sound comes from.
In order to cause the vocal chords (aka vocal folds) to vibrate, we must force (there's that word again but in a new context) air across them by exhaling.  The process of forcing air across the vocal chords causes them to vibrate and using the muscles that control the vocal chords to change their shape, allows us to alter the pitch of the sound produced by air passing over our vocal chords.
In order to get more volume, it is necessary to increase the intensity of the vibration of the vocal chords.  This requires a larger and more powerful burst of air to be passed across the vocal chords by exhaling more forcefully.
Again using the analogy of a guitar string, to get more volume you must pluck the string more forcefully to cause it to oscillate in a wider pattern.  Plucking the string with more force does not change the note, only the volume.
Now to explain why more air is required to sing high notes - whether in head voice or falsetto.  To sing higher notes, your vocal chords must be stretched tighter.  Think of what happens as you tighten a guitar string.  As you turn the tuning peg to tighten the string, the pitch continues to rise.  This is because the tighter string will vibrate more rapidly - thus producing a higher frequency sound wave.
Vocal chords work similarly (tighter = faster vibration).  Tighter vocal chords naturally will require more air pressure to cause them to vibrate because - well they are tighter.  So to belt out the high notes, you must force a more powerful burst of air across the vocal chords than will be required to sing a lower note at the same volume.

... does it continue to become more significant the louder you get? Does it apply to head voice & falsetto as well as chest voice?

The main difference between chest/mixed/head voice and falsetto, is that in falsetto - the vocal folds are not pulled together so they are touching.  So the air is more easily passed between the chords and that's why falsetto sounds more "breathy".  It's also why you can hit the high notes in falsetto without quite as much air pressure.
However regarding singing high notes at a louder volume - since it requires a larger burst of air to both increase volume and vibrate the tighter vocal chords, it is difficult to sing high notes quietly - UNLESS you use falsetto.  The larger burst of air required to vibrate the tighter vocal chords will simultaneously serve to increase the volume.  That's why you see many professional singers pull away from the microphone when they are hitting the highest notes.  They can't sing them at the same moderate volume as the midrange and lower notes.  Thus hitting the highest notes in your non falsetto range may also require you to sing with maximum volume as well.  Low notes can be sung with less volume using less air, but more air can be added to increase volume if desired.
Since falsetto involves passing air across vocal folds that are not tightly touching, it's easier to cause them to vibrate because you are not forcing air between vocal folds that are pulled together.  So you can actually sing the high notes rather quietly when using falsetto.  But you will notice that you won't be able to produce quite as much volume with falsetto.
Answer: I saw that too and have a problem with the term "forcing".  FORCING air through your throat implies tension either in your throat or other parts of your body. I did not want any future visitors to the site to read that and get the wrong idea so I want to put this concept into a more proper perspective.
It does require more air being exhaled to sing high notes than low notes because the vocal chords are stretched tighter to sing higher notes (like stretching a rubber band).  Tighter vocal chords require more air to vibrate them than looser ones.
But I believe it is better to discuss how to allow the body to more naturally and effortlessly push more air across your vocal chords instead of "forcing" air "through your throat".
You never want to tense your throat muscles in a way that constricts your throat at all and particularly don't want to tense them to the point where you feel you are needing to "force" air through your throat.  Tightening or restricting the the throat is not required to tighten the vocal chords.  Without going into a discourse on physiology, the lengthening and shortening of the vocal folds (aka vocal chords) is controlled by the cricothyroid muscle and thyroarytenoid muscle.
Breath support is a very important part of singing. Proper training to build the muscles that support the diaphragm and proper technique developed through specific vocal exercises and practice - will give you the ability to push more air across your vocal chords with less effort, force or tension.
I used to constrict my throat and force air through it in an attempt to hit the higher notes.  Many singers have a tendency to do that in the mistaken belief that it helps tighten the vocal folds for the high notes.   I found that I was straining and damaging my voice by doing this and losing some tone and control.  I have learned that relaxing the throat while singing the high notes prevents damaging stress on my vocal chords and the rest of my body - and improves the quality of my singing.
I also notice that if I am singing in head voice or falsetto and constricting my throat, I have less volume.  If I relax my throat to allow more air to flow across my vocal chords with less resistance from a constricted throat, the volume goes up.  Try it yourself.  Start singing a high note in falsetto while tightening your throat and then consciously relax your throat as you sustain the note and watch the volume increase.
With the proper vocal exercises, you can learn to tighten your vocal folds to sing high notes without straining or constricting your throat.
It is true that in order to increase volume produced by your voice at either end of your range, you will need to exhale a greater amount of air to pass across your vocal chords and into the resonators in your head.  But this does not mean you should feel as if you are forcing anything.
Again the key is learning proper technique and developing better breath support to train and enable your body to push more air across your vocal chords with less effort.  This is best accomplished with lessons or with a qualified vocal coach.  There are also many good lessons for free on YouTube.
Answer: Yes and no. The more air you use, the louder you are, but falsetto and chest voice are two different techniques.
More air means more volume when using proper singing technique and is required to make your voice sound full. The deeper you get, the more air you need. When going below your "natural range" to the deeper notes you can sing, your voice sounds very airy, but not necessarily loud. However, going up to falsetto requires little air and sounds very loud. But why?
Frequency is one possible answer. High frequencies are perceived louder than low frequencies by the human ear.
So in order to become louder when singing deep notes, more air is required. The deeper you get, the quieter you become, the more air you need. Singing loudly does not affect your range on the deepest notes, but it does in fact have a huge impact on high notes. High notes require a lot of pressure and your chest voice can be expanded to the top when "going all in".
When singing timidly, less air is used to sing and it can become very difficult to reach a high note with your chest-voice if the needed air is not given. However, when using falsetto (which is one of the techniques that requires the least air amount), singing timidly already provides the needed air, which makes it possible to sing.
Singing in general doesn't require a lot of air. More air does make your singing louder, but can make it sound bad, when used at the wrong place. A falsetto with too much air would sound very transparent and thin, as well as deep tones with only a little amount of air.
Forcing yourself into singing loudly is not always the best option. If you're singing in the middle of your range, the "the louder the better"-rule fully applies, high notes require the most power. But when rumbling very deep notes, loudness becomes very tricky due to the needed air and needs a lot of practice. Falsetto on the other hand is very loud with little effort, due to its high frequency.
Short answer to your question:
Yes, more air means more volume, but the higher you go, the lesser air you need to go loud.


Estimating demographics from internet activity

Question: I'm looking for research papers on estimating demographic information (age, wealth, location, gender etc.) out of internet activities (preferably social network activity or browser history).
Where would be a good place to look for?
Answer: Last summer, Kaggle ran a competition to predict a users psychopathy,  Machiavellianism, Narcissism etc. using only Twitter data. You can see the competition and results here:

personality competition
psychopathy

I recall there was a published paper on the psychopathy prediction, here:
http://www.onlineprivacyfoundation.org/research_/Sumner_Predicting_Dark_Triad_Traits_from_Twitter_Usage_V5.pdf
Answer: Stuff that I found so far:
Demographic Prediction Based on User's Browsing
Behavior
A Machine Learning Approach to Twitter User Classification
Classifying Latent User Attributes in Twitter