Estratégia para diminuir repetição de código c#

Question: Estou precisando diminuir a quantidade de métodos na minha controller que tem praticamente o mesmo código, o que diferencia eles é o método chamado na hora do GET.
Exemplo:
Classe: ConsultaController
<code>[HttpGet("GetArquivoBaixaVert")]
    public HttpResponseMessage GetArquivoBaixaVert([FromQuery] int? idHeader)
    {
        var response = new ResponseConsulta<ArquivoBaixaVert>();

        try
        {
            if (idHeader == null)
            {
                response.StatusCode = "400";
                response.Descricao = "Dados Enviados nulos ou inválidos";

                return FactoryResponseMessage(HttpStatusCode.BadRequest, response);
            }

            using (var negocio = new ArquivoRecNegocio(""))
            {
                response.Data = negocio.ListarArquivoBaixaVert(idHeader.Value);
            }

            if (response.Data.Count == 0)
            {
                response.StatusCode = "404";
                response.Descricao = "Não foram encontrados arquivos com o id enviado";

                return FactoryResponseMessage(HttpStatusCode.NotFound, response);
            }

            response.StatusCode = "200";

            return FactoryResponseMessage(HttpStatusCode.OK, response);
        }
        catch (Exception e)
        {
            response.StatusCode = "500";
            response.Descricao = $"Erro ao processar, contate o administrador, exceção: {e.Message}";

            return FactoryResponseMessage(HttpStatusCode.InternalServerError, response);
        }
    }
    #endregion

    #region GetArquivoCnab500RemessaFromtis
    [HttpGet]
    public HttpResponseMessage GetArquivoCnab500RemessaFromtis([FromQuery] int? idHeader)
    {
        var response = new ResponseConsulta<ArquivoCnab500RemessaFromtis>();

        try
        {
            if (idHeader == null)
            {
                response.StatusCode = "400";
                response.Descricao = "Dados Enviados nulos ou inválidos";

                return FactoryResponseMessage(HttpStatusCode.BadRequest, response);
            }

            using (var negocio = new ArquivoRecNegocio(""))
            {
                response.Data = negocio.ListarArquivoCnab500RemessaFromtis(idHeader.Value);
            }

            if (response.Data.Count == 0)
            {
                response.StatusCode = "404";
                response.Descricao = "Não foram encontrados arquivos com o id enviado";

                return FactoryResponseMessage(HttpStatusCode.NotFound, response);
            }

            response.StatusCode = "200";

            return FactoryResponseMessage(HttpStatusCode.OK, response);
        }
        catch (Exception e)
        {
            response.StatusCode = "500";
            response.Descricao = $"Erro ao processar, contate o administrador, exceção: {e.Message}";

            return FactoryResponseMessage(HttpStatusCode.InternalServerError, response);
        }
    }
</code>
Percebe-se que o código é praticamente o mesmo, o que vai muda é a chamada negocio.ListarArquivoBaixaVert e negocio.ListarArquivoCnab500RemessaFromtis.
Dentro dessa controller existem vários métodos GET com essas mesmas repetições.
Qual a melhor maneira de fazer com que isso fique em um único método? De repente algum método genérico? É possível?
Comment: As classes de controller devem ser filhas de uma superclasse, não? Você pode criar um método `protected` na superclasse, que recebe como parâmetros essas poucas diferenças, e nos controllers filhos, você simplesmente chama o método "genérico".
Answer: A minha ideia foi pegar as duas partes diferentes do dois metodos que são
var response = new ResponseConsulta();
response.Data = negocio.ListarArquivoBaixaVert(idHeader.Value);
Usei metodos genericos para preencher os dois valores e a partir disso eu construo a mensagem http padrão passando esses dois parametros para um metodo generico que vai ler e retornar um erro de acordo com a logica implementada, como não tinha todos os valores do seu código pode ser que eu não tenha feito um código compilavel mas acredito que com pequenos ajustes possa resolver o seu problema mas acredito que a abordagem possa ser essa.
<code>[HttpGet("GetArquivoBaixaVert")]
        public HttpResponseMessage GetArquivoBaixaVert([FromQuery] int? idHeader)
        {
            var response = retornaResponseConsulta(new ArquivoCnab500RemessaFromtis());
            response.Data = retornaListarNegocio<ArquivoCnab500RemessaFromtis>(new ArquivoCnab500RemessaFromtis(), idHeader);
            return RetornarErroMapeado(response, idHeader);
        }

        [HttpGet]
        public HttpResponseMessage GetArquivoCnab500RemessaFromtis([FromQuery] int? idHeader)
        {
            var response = retornaResponseConsulta(new ArquivoCnab500RemessaFromtis());
            response.Data = retornaListarNegocio<ArquivoCnab500RemessaFromtis>(new ArquivoCnab500RemessaFromtis(), idHeader);
            return RetornarErroMapeado(response, idHeader);
        }
        // esse string tem que ser o tipo de response que como vc declarou var eu nao consegui descobrir
        public HttpResponseMessage RetornarErroMapeado(string response, int idHeader)
        {
            try
            {
                if (idHeader == null)
                {
                    response.StatusCode = "400";
                    response.Descricao = "Dados Enviados nulos ou inválidos";

                    return FactoryResponseMessage(HttpStatusCode.BadRequest, response);
                }

                if (response.Data.Count == 0)
                {
                    response.StatusCode = "404";
                    response.Descricao = "Não foram encontrados arquivos com o id enviado";

                    return FactoryResponseMessage(HttpStatusCode.NotFound, response);
                }

                response.StatusCode = "200";

                return FactoryResponseMessage(HttpStatusCode.OK, response);
            }
            catch (Exception e)
            {
                response.StatusCode = "500";
                response.Descricao = $"Erro ao processar, contate o administrador, exceção: {e.Message}";

                return FactoryResponseMessage(HttpStatusCode.InternalServerError, response);
            }
        }

        private object retornaResponseConsulta<T>(T? objectResponse)
        {
            switch (objectResponse)
            {
                case ArquivoCnab500RemessaFromtis:
                    return new ResponseConsulta<ArquivoCnab500RemessaFromtis>();
                case ArquivoBaixaVert:
                    return new ResponseConsulta<ArquivoBaixaVert>();
                default:
                    return null;
            }
        }

        public List<String> retornaListarNegocio<T>(T? objectResponse, string idHeaderValue)
        {
            List<String> retorno = new();
            switch (objectResponse)
            {
                case ArquivoCnab500RemessaFromtis:
                    using (var negocio = new ArquivoRecNegocio(""))
                    {
                        retorno = negocio.ListarArquivoCnab500RemessaFromtis(idHeader.Value);
                    }
                    break;
                case ArquivoBaixaVert:
                    using (var negocio = new ArquivoRecNegocio(""))
                    {
                        retorno = negocio.ListarArquivoBaixaVert(idHeaderValue);
                    }
                    break;
                default:
                    return null;
            }

            return retorno;
        }

</code>


how can I turn nested dictionary into flat dictionary and sum values with duplicate keys?

Question: here is my dictionary:
d = {'dicta':{'a':1,'b':2,'c':3}, 'dictb':{'a':2,'b':3,'c':1}, 'dictc':{'a':2,'b':5,'c':9,'d':10}}

{'dicta': {'a': 1, 'b': 2, 'c': 3}, 'dictb': {'a': 2, 'b': 3, 'c': 1}, 'dictc': {'a': 2, 'b': 5, 'c': 9, 'd': 10}}

What I want to do is combine these nested dicts into a flat one and also sum the values to get:
{'a': 5, 'b': 10, 'c': 13, 'd': 10}

I can already achieve this using the below code:
out = {}
for k,v in [[k2,d[k1][k2]] for k1 in d for k2 in d[k1]]:
    if k in out.keys():
        out[k] = out[k] + v
    else:
        out[k] = v

However as you can see it isn't very elegant. There must  be a better way! (Raymond Hettinger :D).
I can also do a dict comprehension which obviously only keeps one entry for each key:
out = {k2:d[k1][k2] for k1 in d for k2 in d[k1]}

output: {'a': 2, 'b': 5, 'c': 9, 'd': 10}
or a list comprehension that at least gives me everything I want to combine:
out = [{k2:d[k1][k2]} for k1 in d for k2 in d[k1]]

output: [{'a': 1}, {'b': 2}, {'c': 3}, {'a': 2}, {'b': 3}, {'c': 1}, {'a': 2}, {'b': 5}, {'c': 9}]
Which feels like I'm getting close...
Is there a way to combine these the way I want in a really elegant way that I am just unaware of?
Something like : out = {k2:d[k1][k2] for k1 in d for k2 in d[k1] with combined = True} (obviously doesn't make sense but to illustrate the point)
Looking for the cleanest way to do this
Answer: You can use collections.defaultdict:
from collections import defaultdict
d = {'dicta':{'a':1,'b':2,'c':3}, 'dictb':{'a':2,'b':3,'c':1}, 'dictc':{'a':2,'b':5,'c':9,'d':10}}
_d = defaultdict(int)
for a in d.values():
  for c, j in a.items():
     _d[c] += j

print(dict(_d))

Output:
{'a': 5, 'b': 10, 'c': 13, 'd': 10}

Shorter solution using itertools.groupby:
from itertools import groupby
r = sorted([i for b in d.values() for i in b.items()], key=lambda x:x[0])
result = {a:sum(c for _, c in b) for a, b in groupby(r, key=lambda x:x[0])}

Output:
{'a': 5, 'b': 10, 'c': 13, 'd': 10}

Comment: very nice.. doubt this can be improved but, I can't accept for another 5 min so we'll see :D
Answer: Another way using collections.Counter:
from collections import Counter

sum(map(Counter, d.values()), Counter())

Output:
Counter({'a': 5, 'b': 10, 'c': 13, 'd': 10})


Which of the following conditions imply that $G$ is abelian?

Question: Let $G$ be a group of order $n.$ Which of the following conditions imply
that $G$ is abelian?
a. $n = 15.$
b. $n = 21.$
c. $n = 36.$
I can see $a$ is true (since a cyclic group of order $3\times 5$) and $b$ is false (by considering $D_{36}$). But I'm skeptical about my solution for $b$ since the answer says group of order $21$ is not necessarily abelian even though

if I consider $H,K$ to be the sylow 3 and sylow 7 subgroup then $G\simeq H\times K.$ Since $H,K$ are abelian so is $G.$

I don't know where did I go wrong?
Comment: @DominicMichaelis, I can't see why you claim (c) is abelian and even less why the reason you mention would so imply...
Comment: @DominicMichaelis no, that is not even close to being correct.
Comment: @DominicMichaelis the first part is right (square of prime). As soon as you add more primes, it becomes wrong. You need more conditions on the primes than being distinct.
Comment: How do you get $G\simeq H\times K$?
Comment: For order $21$, consider a semidirect product using that $\rm{Aut}(C_7)$ has a subgroup of order $3$.
Comment: @TobiasKildetoft Isn't there any other way? I don't know semidirect product.
Comment: @Tobias we did prove it in introduction to algebra. If it is not close to being correct tell me a counterexample
Comment: http://www.proofwiki.org/wiki/Group_of_Order_Prime_Squared_is_Abelian
Comment: @TobiasKildetoft and what would those be ?
Comment: @DominicMichaelis, yes: every group of order the square of a prime is abelian, but that does not mean that a group whose order is the product of two squares of primes is: not even close as mentioned already! For example, there are 10 non-abelian groups of order 36...!
Comment: I think that by $\,\prod p_i^2\;$ and etc. you meant *direct product*, which is not what we're talking about here.
Comment: you please verify whether you really mean "b is false (by considering $D_36$)" in your question.. I guess you want to say "c is false by considering $D_36$".
Comment: @PraphullaKoushik: Yes the OP meant what you noted. "c" is not necessarily abelian.
Comment: btw, i mean $D_{36}$ and not $D_36$ :P
Comment: I have up voted this question as it made me to think i forgot my group theory for some time :P.. I guess it is very natural to come to the conclusion as posed in the OP.. I was very confused for half an hour where did it go wrong ??
Comment: Lesson: If you choose to say "by that argument, $S_3$ is abelian," your next sentence should not effectively argue that $S_3\times S_3$ is abelian. :-)
Comment: @DonAntonio oh yes sorry I was half asleep. Sorry for the confusion
Answer: For a concrete example of a non-abelian group of order $21$, let us first consider a broader class of groups, namely those of affine transformations of a finite field.
So let $F$ be a finite field of order $q$ and consider the set of maps $F\to F$ of the form $x\mapsto ax + b$ with $a\neq 0$. It is easy to check that this set forms a group under composition (since these maps are bijective), and this group has order $q(q-1)$.
If $G$ is a subgroup of the multiplicative group of $F$, then restricting to those maps with $a\in G$ gives a new group, with order $q|G|$.
For the specific example of order $21$, we can take the finite field of order $7$ (so $\mathbb{Z}/7\mathbb{Z}$) and the subgroup to be $\{1,2,4\}$. You should then check that the resulting group is not abelian.
The above class of groups is a great way to construct examples of non-abelian groups of various orders.
Answer: In a group of order $\;15=3\cdot 5\;$ , both Sylow subgroups must be normal (and thus unique) by direct application of Sylow theorems, and this means the group is a direct product of these two subgroups, each of which is abelian (even cyclic) and thus the whole group also is abelian (and cyclic, in fact) .
In the other two cases we can construct a non-abelian group of that order using semidirect products. but since you haven't yet covered this I won't go further.
Comment: Aren't $D_{36}$ work for c?
Comment: I don't understand: what does "work" mean here? What you wrote in your question meant "for what values of $\,n\;$ a group of that order *necessarily* is abelian?", and that's what I addressed in my answer: there is only one group of order $\;15\;$ up to isomorphism and it is the cyclic one, and thus abelian, one. In the other two cases there is at least one non-abelian group of that order.
Comment: I meant to say that I can see dihedral group of order $36$ is nonabelian. So a group of that order $36$ is not necessarily abelian whence $c$ can be removed from the consideration.
Answer: You can construct the (non-abelian) semidirect product of $C_7$ and $C_3$ as follows: We view $C_7$ as the additive integers $\text{mod}7$ and $C_3$ as the subgroup of $\Bbb Z_7^*$ of order $3$, this is the multiplicative group $\{1, 2, 4\}$. Then $G=\Bbb Z_7\times \{1, 2, 4\}$ and multiplication is defined by $$(a,b)*(c,d)=(ad+c,bd).$$ Check that the multiplication is associative, then the neutral element is $(0,1)$ and inverses are given by the rule $(a,b)^{-1}=(-ab^{-1},b^{-1})$.
Answer: I wonder you already have an answer for some part of your Question :

If I consider $H,K$ to be the sylow 3 and sylow 7 subgroup then $G\cong H\times K$. Since $H,K$ are abelian so is $G$.

i remember you posed similar question asking to verify a proof that "any group of order $85$ is cyclic".
to show $G\cong H\times K$ it is not enough to show $H\leq G$, $K\leq G$ and $|H\times K|=|G|$
you need to prove that $H\unlhd G$ and $K\unlhd G$
In general it is not true that any sylow-$3$-subgroup in a group of order $21$ is normal (you please check it).
So, what you say i.e., $G\cong H\times K$ is not true in general.
So, there may possibly exist a nonabelian group of order $21$.
I hope you are happy now at least that you came out from a wrong notion.
Now expecting the possibility of existence of non abelian group :

I would suggest you to make a copy of (more generalized) group of order $21$ in a way similar to that you construct a dihedral group. (this is what comes to my mind if i want to construct non abelian group if i am sure there does exist a possible non abelian group. though i fail most of the times (:P) i feel one should not fear of getting defeated)

So, what we do in dihedral group $D_{2n}$ is take an element $r$ of order $n$ and an element $s$ of order $2$ and generate the group with an extra condition that $srs^{-1}=r^{-1}$.
With same motivation, as $21=3.7$ i take an element of order $7$ and an element of order $3$ and write very similar relation as that of  $srs^{-1}=r^{-1}$.
I know there exists an element of order $7$ (thanks to cauchy theorem and sylow(??)) say $a$ and an element of order $3$ (thanks to cauchy theorem and sylow(??)) say $b$.
we have $a,b\in G$ with $'a'$ generator of sylow $7$ subgroup and $'b'$ a generator of sylow $3$ subgroup.
As we know that any sylow $7$ subgroup is normal, $bab^{-1}\in \langle a\rangle$ (??)
So, $bab^{-1}$ has to be one of $1,a,a^2,a^3,a^4,a^5,a^6$
one see that $bab^{-1}\neq 1$ in which case $a=1$ and $bab^{-1}\neq a$ (in which case $ab=ba$ and so $G$ is abelian and we do not want that).
So the next option is $bab^{-1}=a^2$, I do not see any problem with this and i see that i have exactly $21$ elements (??) in $\{\big<a,b\big> : |a|=7, |b|=3 ,bab^{-1}=a^2\}$.
So, I have got a non abelian group of order $21$ with

$G=\{\big<a,b\big> : |a|=7, |b|=3 ,bab^{-1}=a^2\}$

please try to check what would happen if $bab^{-1}=a^i$ for $3\leq i\leq 6$ (which i have not checked out)
P.S : I tried my best to use nothing more than cauchy/sylow theorem as you said you are not familiar with semi direct product. please let me know if you see any traces of that as i also want to write it down more elementarily.


Macintosh C Creating a navigation window to choose an app

Question: I'm writing a C program for mac, and I need to allow the user to choose an application to send an apple event to. I can create a navigation window, using NavCreateChooseFileDialog(), but I can't get it to enable any .app files. If I restrict the types using NavDialogSetFilterTypeIdentifiers, it will only allow me to select applications like MS Office, that don't have .app in the folder name. Everything else is greyed out.
Any ideas?
Answer: Remember that .app bundles are directories, so you may need to enable some sort of allow-directories (or, more likely, enable-bundles) option.
I'm sorry that I can't offer more specific help. I started with Carbon, but never did touch Navigation Services.
Comment: Yes, I've tried various NavDialogSetFilterTypeIdentifiers settins and nav...chooseObject, and it didn't help.
Answer: Make sure to set the flag kNavSupportPackages in inOptions.optionFlags for NavCreateChooseFileDialog, and put 'APPL' in the types list (might as well still use that param instead of NavDialogSetFilterTypeIdentifiers(), that way you'll run on 10.3-) and you should be good to go, I just tried.
Alternatively, if you don't mind using Cocoa, you can use -[NSOpenPanel runModalForTypes:[NSArray arrayWithObjects:@"app", nil]] (which also lists non-.app applications), and then you're only one FSPathMakeRef((UInt8*)[path fileSystemRepresentation], &fsRef, NULL); away from an FSRef.
Do remember that, in either case, the file you get may be an alias so you will have to try and resolve aliases.
Answer: This works for me:
NSOpenPanel * panel = [ NSOpenPanel openPanel ] ;
panel.allowedFileTypes = @[ (__bridge id)kUTTypeApplication ] ;

[ panel runModal ] ;


Let k be a positive integer. Show that the function $a^5+a$ takes on every residue class mod $5^k$

Question: for any $0 \le b \lt 5^k$, there exists an integer $a$ such that $a^5+a \equiv b$ mod $5^k$.
I used induction but stuck on the inductive step.
Comment: Induction on $k$, I suppose?
Answer: If you are familiar with Hensel lifting, you will note that the solution below is a special case of lifting.
It is easy to verify that for any fixed integer $b$, the congruence $x^5+x\equiv b\pmod{5}$ has a solution. Suppose now that there is a solution modulo $5^k$. We show there is a solution modulo $5^{k+1}$.
Suppose that $a^5+a\equiv b\pmod{5^k}$. We produce a solution modulo $5^{k+1}$. Let $a^5+a=b+q5^k$.
We look for a solution of shape $a+t5^k$. So we want
$$(a+t5^k)^5+a+t5^k  \equiv b\pmod{5^{k+1}}.$$
Expand the left-hand side, and note that $(a+t5^k)^5\equiv a^5\pmod{5^{k+1}}$.
So we want
$$a^5+a+t5^k\equiv b\pmod{5^{k+1}},$$
or equivalently
$$q5^k+t5^k\equiv 0\pmod{5^{k+1}},$$
or equivalently
$$q+t\equiv 0\pmod{5}.$$
The above congruence has a solution. This completes the induction step.
Remark: Since we now know that we can take $t=-q$, we can avoid much of the calculation and just write down the lifted solution. But I wanted to give a proof that mirrors the general lifting argument.
Comment: I think you mean $a^5$ and not $a^k$
Comment: @ArunKumar: Many thanks! And I had done it twice.


prove sequence is convergent

Question: $(a_n)_{n=1}^\infty$ is a sequence where $(a_{2n}) \le (a_{2n+2})$ and $(a_{2n+1}) \ge (a_{2n+3})$, i have to prove that $a_n$ is covergent if and only if $\lim_{n\to\infty}$ ($a_{n+1}- a_n)$=0.
now i proved that if $a_n$ is convergent then lim $(a_{n+1} - a_n)$=0 by proving that if $a_n$ is convergent to limit L then $a_{n+k}$ is also  convergent to L, but im not sure how to prove that if the limit=0 then $a_n$ is convergent, i know i have to do something with the sub-sequences since thats where im at, but im not sure how to proceed.
Answer: Hints: $(a_{2n})$ is increasing and $(a_{2n+1})$ is decreasing.  If $a_{n+1}-a_n <1$  for $n \ge k$ then $a_{2n}\le a_{2n+2}<a_{2n+1}+1 \le a_3+1$ as long as $2n+1\ge k$. Thus, $(a_{2n})$ is bounded above. Similarly, $(a_{2n+1})$ is bounded below. These sequences have  limits. Show that the two limits are equal.
Comment: I'm sorry I'm not quiet following you, but wouldn't it be $a_{2n+1} +1 \le a_3 +1$ since the n starts at 1? also is there a specific reaosn we're assuming $a_{n+1} - a_n \lt 1$ ? thanks
Comment: Less than any  $\epsilon$ will be fine. You are right about $a_3+1$. @S. M

prove sequence is convergent


Splitting Drupal commerce order for easier shipping

Question: During shipping we generally need to split the orders based on the availability of the products. Considering the order contains two products but only one product is available, we would like to split the order such that we can ship one product now and we can ship the the product later. Both split orders will contain same address and other details.
Are there any module that does this?
Answer: I'm not sure you need to consider this as order splitting. I'm working on a project currently that will make use of the Commerce Shipment module to handle splitting an order into shipments for fulfillment. It can accommodate either a single shipment per order or multiple if necessary.
Comment: Thanks. Coming from @ryan I will consider this as a closure. Can you please share the link to sandbox module that you are working. I can take a look at it and plan around that :)
Comment: I got commit access to the repository I linked above, so I'll be making my updates directly to it.


Allow comments on profile pages

Question: What are the ways to allow comments on user profile pages in Drupal 7? There is a profile content module, which unfortunately is not available for Drupal 7.
Comment: That question was for drupal 6.
Comment: No. Please check it once. OP clearly mentioned that it for D7. May I know how could you justify that the question was asked for D6?
Comment: @KrishnaMohan Subliminal messaging - cast your eye to the left of that page...3 sixes in a vertical row ;)
Comment: @Clive  I just noticed that ;) :) :)
Comment: @KrishnaMohan my bad. I thought that it was marked as a duplicate of this (http://drupal.stackexchange.com/questions/10767/add-comments-to-profiles) which was what was shown as a duplicate suggestion when I was typing the question. I was in a hurry to cross section. My apologies.
Comment: @RanaPrathap Hey, no problem. I just wanted to intimate you. :) :)
Answer: I think you can find an answer in this similar question here: How do I enable comments for user profiles?
Apparently, Profile2 module allows that functionnality.
Answer: Generally Drupal allows comments on nodes.
There is a module in D7 module User Proifile Comments which does the job.
You can also check this https://www.drupal.org/node/68340 which was a more customized way.

Allow comments on profile pages


destination host unreachable virtualbox

Question: Basically i am trying to implement this on this picture
I have my static ips assigned more or less like this and i can ping from my internal network to my 2 ports in my router without any problems.
But for some reason when i try to use my external network to ping the router it gives me

destination host unreachable

here are my configuration images :
Router_1

Router_2

Internal VM

External VM

how can i accomplish this in a way all my vm's can ping each other?
Comment: How is the hypervisor configured?  It may be that the VMs are not virtually connected.  Also, consider not posting large screenshots when simply posting interface config...
Comment: how do i connect the virtual machines? i am using virtualbox
Comment: Yes.  How are the virtual interfaces configured in the hypervisor (virtualbox)?
Comment: router vm as 2 adapters both in ''bridged adapter'' one with the wlan0 and the other with eth0
the other machines only have one bridged adapter with wlan0
Answer: i had a misconfiguration in my vm settings. changed the name of the connection from eth0 to wlan0 witch is exactly the name from the other vm

destination host unreachable virtualbox


Pair of numbers using pigeon hole principle

Question: n ∈ N, A ⊆ {1, . . . , 2n}, |A| = n + 1. Show that:
a) In A there is a pair of numbers whose sum is equal to 2n + 1.
b) In A there is a pair of relatively prime numbers.
c) In A there is a pair of numbers, such that one is a multiple of the other.
For the first part, I started by making pairs of numbers whose sum equals 2n + 1, which is literally the first number and the last one in the set A,
{2n + 1, 2n - 1 + 2, 2n - 2 + 3 ...}
I'm not sure how to prove that there exists this pair, when it clearly does.
I'm not sure how to go about part b) and c) any hint would be much appreciated.
Comment: For (b) you can probably use that $n$ and $n+1$ are relatively prime for all $n$
Comment: For c) see: [Using Pigeonhole Principle to prove two numbers in a subset of $[2n]$ divide each other](https://math.stackexchange.com/q/315050).
Answer: For the first part, you started well. You need to make pairs that add up to $2n+1$. Except $(1,2n)$, we can have $(2,2n-1)$ and more. In general $(1+d,2n-d)$, where $d=1,2,...,n$. So, there are $n$  pairs. Having $n$ pairs, taking $n+1$ numbers would force to take two numbers from a same pair.
For the second part, notice that any pair $(a,a+1)$ are mutually prime. So, make pairs of consecutive numbers.
For the last part, You need to make sets as the following. In $\{1,2,...,2n\}$, there are exactly $n$ odd numbers. Consider $n$ empty sets and put one of the $n$ odd numbers in each of them. Then, if $\{x\}$ is one the sets, complete the set as below.
$\{x\times 2^{k}|k\in\mathbb{N}\cup\{0\} , x\times 2^{k}\leq2n\}$
It can be shown that, by this way of constructing the sets, no repetition of numbers would happen. Also, it would cover all the numbers.
Answer: $$ \begin{array}{rcl} 2n & \longleftrightarrow & 1 \\ 2n-1 & \longleftrightarrow & 2 \\ 2n-2 & \longleftrightarrow & 3 \\ 2n-3 & \longleftrightarrow & 4 \\ & \vdots \end{array} $$
If your set $A$ contains at most one number from each of these $n$ pairs, then you have $|A|\le n.$
Answer: Let's put the given data as
$$
\left\{ {\begin{array}{*{20}c}
   {U = \left\{ {1,\; \ldots ,\;2n} \right\}} & {\left| U \right| = 2n}  \\
   {A \subseteq U} & {\left| A \right| = n + 1}  \\
   {B = U\backslash A} & {\left| B \right| = n - 1}  \\
 \end{array} } \right.\quad
$$
Now, consider the ordered couples, e.g. $(a,b)\;|\,a \leqslant b$, of elements of $U$ that satisfy a given property.
If (at least) one of the elements of the couple pertains to $B$, then the whole couple cannot pertain to $A$.
So if $B$ can accomodate at least one distinct element per each couple, then all the couples are "destroyed", i.e. none  will pertain to $A$.
We do not loose of generality if we perform this check on the first (distinct) element of each couple, since we can always switch the elements.
Since the cardinality of $B$ is $n-1$, that means that if within the ordered couples with the given property, the count of those that have
a distinct first element is less than $n$, then there could be the case that $B$ contains all such elements, leaving no couple for $A$.
Viceversa, if they account to $n$ or more, than at least one couple will remain out and will end in $A$.
Now, also taking  in consideration the other answers, for the proposed properties we have

a) the ordered couples summing to $2n+1$ are $(1,\,2n)\; \cdots \;(n,n+1)$, for a total of $n$ with all distinct first el. $\quad  \Rightarrow \quad \text{demonstrated}$
b) the ordered couples with coprime elements are at least those given by $(n \, ,n+1)$, for a total of $n \leqslant 2n-1$,  with all distinct first el. $\quad  \Rightarrow \quad \text{demonstrated}$
c) the ordered couples  with one element multiple of the other are at least those given by $(1 \, ,n+1)$, for a total of $n \leqslant 2n-1$,  with all distinct second el., and switching the order $\quad  \Rightarrow \quad \text{demonstrated}$


Create custom theme for module

Question: I've creating an intranet module for Drupal 8 and I want to use a custom theme for it, like an admin theme(with page/node/field templates) where I can map region like menu, header, footer... but only for my module.
I didn't find any specific doc about this.
Thanks for your help!
Answer: You cannot specify region on your module, but you can custom your page or your block.
Regions are specify into main theme.
First, you need to create a folder on your module root directory :

myModule/templates

Inside, you ll put all your custom template.
For example :

page1.html.twig
page2.html.twig

Then you need to declare all your templates :

In myModule.module :

<code>/**
 * Implements hook_theme().
 */
function myModule_theme() {
  return [
    'page1' => [
      'template' => 'test',
      'variables'=>array('test'=>NULL),
      'render element' => 'children',
    ],

      'page2' => [
          'template' => 'page2',
          'render element' => 'form',
      ],

  ];
}
</code>
And after, in your controller or your form :
<code>return $build +  [
  '#theme'=>'page1',
  '#test'=>"its content for my variable inside my template",
];
</code>
Comment: Yeah thanks, but that's what I do for now and I don't like this way, that make no sense to include every part of the module ( header, footer, menu, aside) on every page it should be the opposite. I hope someone could find a solution.
Answer: Another option would require creating a theme (in addition to your module).  Then have your module indicate it uses that theme.  Here is a nice article on how to do this https://speedandfunction.com/switching-themes-programmatically-drupal-8/
In this scenario, you would have your main theme and the theme used by your module.  You could indicate that the theme used by your module was a sub-theme (https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme) of your main theme which could reduce some theme coding management.
Comment: I found an article like yours for my needs here : http://annakalata.com/blog/drupal-8-how-switch-theme-based-pages-active-menu I just replace the active menu by my route name. I think I explain it much better.
Answer: If u want custom theme for module u just need to use template suggestions, output content from php and then render it in twig files.

Create custom theme for module


Are arithmetic operations are only defined to base $10$?

Question: I want to know if the simple math operations that we use, per example, $5 + 5$, are only defined on base $10$. If I want to change $5$ to base $3$ and then sum it, or double it, can I do directly $12_{\textrm{base } 3} + 12_{\textrm{base } 3}$?
Comment: what is $(101)^^5$?
Comment: @YujieZha sorry, I did a mistake
Comment: What makes you think that?
Comment: @user251257 I don't know, I'm just asking
Comment: It's exactly the same algorithm as in base 10. Except you do a remainder when the result is bigger than 5 instead of bigger than 10
Answer: You can use the arithmetic operators with any base of numeration whatsoever, and you can even use it with archaic or nonstandard numeral systems. For example: $$\text V + \text V = \text X$$
The important thing is that you and I, reader and writer or vice-versa, understand what base we're working on.
To that end, you can write something like "in the following section, we'll be using the ternary numeral system," and just go ahead and write 12 + 12 = 101. Look for example at this page from Princeton University on binary addition:

Now that we know binary numbers, we will learn how to add them. Binary addition is much like your normal everyday addition (decimal addition), except that it carries on a value of 2 instead of a value of 10.
For example: in decimal addition, if you add 8 + 2 you get ten, which you write as 10; in the sum this gives a digit 0 and a carry of 1. Something similar happens in binary addition when you add 1 and 1; the result is two (as always), but since two is written as 10 in binary, we get, after summing 1 + 1 in binary, a digit 0 and a carry of 1.
Therefore in binary:
0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 10 (which is 0 carry 1)

It would get tiresome if they had to put in a little subscript 2 every time they wanted to put a number in binary in there.
Of course if you want to be extra clear, you can always specify the base in a subscript: $$12_3 + 12_3 = 101_3$$
Apparently there is such a thing as a ternary computer, but most of our computers operate in binary, and they generally convert the results to decimal to display them to us. So there is a difference between doing a calculation in a particular base and displaying it in different base.
The basic principles are the same: you add two positive numbers together, the result is also a positive number, you subtract a number from itself the result is 0, etc.
However, if you depend on tables of addition and multiplication to help you in base 10, then you will need different tables of multiplication to help you in a different base. But the basic principle is the same.
Beware of division, however: $$\frac{1}{3} = 0.3333333333333\ldots$$ But if we're working in duodecimal (base 12), we'd have $$\frac{1}{3} = 0.4.$$ And there are still much subtler issues that can come up.
Answer: Based on my understanding of the question, I do not think there are too much magic here. So for naturally defined summation, itself does not rely on the base-representation of numbers, but it just relies on the numbers it tries to sum.
e.g. 2 + 8 = 10 in base 10, it means, starting from number 2, going forward by 8 steps and find 10 there.
If you represent the numbers in base $3$: $2=2_{(3)}$, $8=22_{(3)}$, and $10=101_{(3)}$.
So you get $2_{(3)}+22_{(3)}=101_{(3)}$, so you start from number $2_{(3)}$, go forward by $22_{(3)}$ steps, and arrive at $101_{(3)}$
Thus
the definition of summation $a+b$ over natural numbers (in the natural sense) should be - starting from $a$, and you find the $b^{th}$ successor of $a$, regardless of how to represent the numbers.
But I think here you might be talking about the calculation rules instead of the definition for summation. So the set of calculation rules for base 10 is of course different for base 3.
To see this: under base 10, we count to 9, and if we want to count up one more, to increment to the higher position; but by contrast, under base 3, we could only count to 2, and if we want to count up one more, we need to increment to the higher position.
Comment: what I mean is, suppose you don't know 8+2=10, on base 10. And you want to do all calculations on base 3. Can you simply do it 2+22 ? Is "sum" property defined to other bases different from 10?
Comment: So as I said in my answer the sum $a + b$ of in the natural sense should be starting from a, and you find the bth successor of a. I think here you might be talking about the *calculation rule* instead of the *definition* for summation. And the set of calculation rule for base 10 is of course different for base 3 - I'll update my answer.
Comment: yes, that's what I mean. The rules are different.
Comment: Yea, I guessed you meant for rules. Hope my update answered your question :)


Right or wrong way to search within XML element with XMLSearch?

Question: Given the following XML:
<cfsavecontent variable="xml">
<root>
    <parent>
        <child>I'm the first</child>
        <child>Second</child>
        <child>3rd</child>
    </parent>
    <parent>
        <child>Only child</child>
    </parent>
    <parent>
        <child>I'm 10</child>
        <child>I'm 11!</child>
    </parent>
</root>
</cfsavecontent>

Is this the best way to loop over each parent and then extract all children from that parent?
<cfset xml = XMLParse(Trim(xml))>

<cfset parents = XMLSearch(xml, "//parent")>

<cfloop array="#parents#" index="parent">

    <cfset parent = XMLParse(parent)>

    <cfset children = XMLSearch(parent, "//child")>

    <cfloop array="#children#" index="child">
        <cfoutput>#child.XmlText#</cfoutput>
    </cfloop>

</cfloop>

The reason I ask is because I've never been able to extract all child elements from the current XML element.
The 'Is this needed?' comment highlights the line I added to make the proceeding line work. But is it possible to to remove this line and somehow change 'XMLSearch(parent, "//child")' to only get child elements from the current 'parent'?
Thanks.
Comment: +1 -- It is indeed kind of counter-intuitive that CF does not seem to honor context in XmlSearch().
Answer: <cfset parent = XMLParse(parent)>

No, it's not. It's even a performance penalty because you create a new DOM this way.
You get an array of XML nodes back from XmlSearch() (why else would you use <cfloop array...?). This means these should be equivalent:

<cfloop array="#parents#" index="parent">
  <cfdump var="#parent#">
</cfloop>

<cfloop from="1" to="#ArrayLen(parents)#" index="i">
  <cfdump var="#parents[i]#">
</cfloop>

To make ColdFusion honor context when searching a node, you need to do:
XMLSearch(parent, ".//child")
-------------------^

If you start an XPath expression with "//", ColdFusion obviously searches the entire document the node belongs to, not just that node's descendants.
But if you are interested in outputting all <child> elements from the document, why not do this instead:
<cfset children = XMLSearch(xml, "//child")>

Comment: Yup, XMLSearch(parent, "//child") gets all children in the document, XMLSearch(parent, ".//child") gets children in the current parent.

Cheers Tom!
Comment: Yup, I get that, but when looping over those parent nodes I want to search within each one.

I've been unable to come up with a version of this line...

... so I thought, turn 'parent' from an XML Element, into an XML document and then the XPath is easier.
Comment: Sorry, commented based on your first draft.

I want all child elements, but only for the current parent.
Comment: Try to search for ".//child" in the loop. Doing "//child" obviously triggers a document-wide search, whereas starting from "." honors context.
Comment: However - looping over all parents, just to output all their children in a loop is pointless. You can select them directly, so I hope it was just an example and your app does something more than just running XmlSearch() in a nested loop. :-)
Comment: Yup, just an example. The question should have mentioned context as that's what I was wondering about. Will test is out...
Comment: Actually I was so sure that it would do what every sane person would expect that I did not even check what XMLSearch(parent, "//child") actually does. But sure enough, it gets it wrong. *sigh*


Is there any rule of thumb to delete a variable in a large data set?

Question: I'm working with a large set as a project for the business analytic course with $10^5$ observations and 170+ variables, some of which come with a missing value proportion of larger than 20%, even more than 95%.
I'm really thinking about under such situation, whether it's necessary to apply any imputation method to those variables rather than simply delete them.
If you could give me any criteria on how could I delete them, thanks in advance!
Answer: It is possible to disregard variables with some missing data from the analysis if you find substitutes for them.
For example, if variable $X$ has some missing observations, but its non missing observations pairwise correlates with variable $Y$, then $X$ could be replaced by $Y$. It is also important to have a theoretical justification to carry on such replacement, in order to avoid spurious correlation.
There are many techniques to find correlated variables such as pairwise correlation (Pearson, Spearman), variance inflation factor (VIF), principal component analysis (PCA), clustering, etc.
If variable $Z$ has 95% of missing data, then there is not enough information even for an exploratory analysis. Better disregard it right away.


What can we say about hypergeometric distribution with unknown $N$?

Question: Hypergeometric distribution describes outcome of $n$ draws without replacement from the urn containing $K$ white balls and $N-K$ black balls. Binomial distribution describes outcome of $n$ draws with replacement with probability of drawing white ball equal to $p$. As total number of balls in the urn increases, hypergeometric distribution converges to binomial.

What if we are drawing $n$ balls from the urn of unknown size with probability $p=\tfrac{K}{N}$ ? Expected value is obvious no matter of $N$, since it is simply $np$. Can we say anything more about the distribution of such draws besides noticing that the lower boundary for it is hypergeometric distribution with $N = n$ and upper boundary is a binomial distribution?
The question is not about simply estimating $N$ since it can be estimated from the data like any other parameter, but it is rather about what can we say about the distribution nonetheless $N$ is unknown?
Comment: @whuber right, I removed this notion not to make it ambiguous.
Comment: Could you elaborate on the difference between "estimating" and "making educated guesses"?
Comment: @whuber I was thinking of situation where you'd need to make some guesses before seeing the data or when seeing only a very small sample, so your estimates would not be very reliable.
Comment: "Guesses before seeing the data" are usually called a *prior distribution,* while "guesses ... when seeing only a very small sample" are still called *estimates.*
Comment: Are you interested in somehow estimating $N$?
Comment: @AlexR. rather in dealing with the fact that $N$ is unknown, since $N$ can be threated as any other parameter and estimated from the data. The question is simply: what can we assume about the distribution if $N$ is unknown?
Comment: https://stats.stackexchange.com/questions/123367/estimating-parameters-for-a-binomial/123748#123748
Comment: @kjetilbhalvorsen thanks, nice answer (alredy +1'd), but how does this relate to this question?
Answer: The simplest way to answer this question is just to state the probability mass function that occurs in the general case, and look at its properties with respect to $N$ (i.e., look at the corresponding likelihood function for the parameter $N$).  The probability mass function for the hypergeometric distribution is:
$$\text{HG}(k|N,K,n) = \frac{{K \choose k} {N-K \choose n-k}}{{N \choose n}} \overset{N}{\propto} \frac{(N-K)!(N-n)!}{N!(N-K -n + k)!}.$$
It is possible to investigate all sorts of properties of the above function, and there are all sorts of things we could potentially say about it.  One interesting property of this probability mass function is that it is quasi-concave in $N$ (see below).  From this result the MLE for that parameter is:
$$\left \lceil{\tfrac{nK}{k}-1}\right \rceil \leqslant \hat{N} \leqslant \left \lfloor{\tfrac{nK}{k}}\right \rfloor.$$
(This gives a unique solution if $\tfrac{nK}{k} \notin \mathbb{N}$, and it gives two solutions if $\tfrac{nK}{k} \in \mathbb{N}$.)  Hence, we see that the MLE estimates $N$ in a way that roughly equalises $\tfrac{n}{N} \approx \tfrac{k}{K}$, with convergence as $n \rightarrow \infty$.  There is probably plently more we could say about this distribution.  It would be interesting to look at what happens once you combine it with various Bayesian priors on $N$.  I will leave it to others to give other insights, but the above seems like an interesting aspect of the distribution to me.

Proof of quasi-concavity: For simplicity, we denote $\phi(N) = \text{HG}(k|N,K,n)$ and consider the other variables to be implicit (fixed) values.  We can then write:
$$\begin{equation} \begin{aligned}
\frac{\phi(N+1)}{\phi(N)} - 1
&= \frac{(N-K+1)(N-n+1)}{(N+1)(N-K-n+k+1)} - 1 \\[6pt]
&= \frac{(N-K+1)(N-n+1) - (N+1)(N-K-n+k+1)}{(N+1)(N-K-n+k+1)} \\[6pt]
&= \frac{(n-k)(N+1)-n(N-K+1)}{(N+1)(N-K-n+k+1)} \\[6pt]
&= \frac{(nN+n-kN-k)-(nN-nK+n)}{(N+1)(N-K-n+k+1)} \\[6pt]
&= \frac{nK-k(N+1)}{(N+1)(N-K-n+k+1)} \\[6pt]
&= \frac{\tfrac{n}{k/K}-(N+1)}{k(N+1)(N-K-n+k+1)}. \\[6pt]
\end{aligned} \end{equation}$$
Hence, we have:
$$\text{sgn} \Big( \phi(N+1)-\phi(N) \Big)
= \text{sgn} \Big( \frac{\phi(N+1)}{\phi(N)} - 1 \Big)
= \text{sgn} \Big( \tfrac{n}{k/K} - (N+1) \Big).$$
Hence, we see that the mass function is increasing for $N+1 < \tfrac{n}{k/K}$ and then decreasing for $N+1 > \tfrac{n}{k/K}$.  This means that the probability mass function is quasi-concave in $N$.


How to hide text character according to size of div

Question: I want to truncate text according to div size
this is the code snippet:

  Lorem Ipsum is simply dummy text of the printing and typesetting industry.
  Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
   when an unknown printer took a galley of type and scrambled it to make a type specimen book.
  It has survived not only five centuries

this is my output:

i want my output to be like:

thank you
Answer:

div {
  white-space: nowrap;      /* new */
  overflow: hidden;         /* new */
  text-overflow: ellipsis;  /* new */
  padding-left: 10px;
  width: 200px;
  border: 1px solid #000000;
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries

More details: Applying an ellipsis to multiline text
Comment: I hope my answer helped you. If it did, consider accepting it (click check mark). If not, feel free to post a comment. Cheers!
Answer: Apply following style to your div.
div{
    padding-left: 10px;
    width: 200px;
    text-overflow: ellipsis;
    overflow: hidden;
    border: 1px solid #000000;
    white-space: nowrap;
}

Answer: You will need to give it a height and use text-overflow: ellipsis;
You can use this class.
.no-overflow {
  padding-left:10px;
  width:200px;
  border:1px solid #000000;
  height: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}


Run SQL package with different parameters at different times of the day

Question: I am trying to run an SQL package from our SQL Server via a scheduled job at different times of the day with different parameters. The package imports property specific information (our company has multiple properties) that is available after a certain time of the day. The package accepts a property code parameter to identify the property information to be imported.
If possible, I would like to re-use one package/job and set up multiple steps that execute at certain times of the day.
Is there a better way to set this up besides using multiple jobs that run the same package with its own parameters?
I would really appreciate some advice, thank you.
Comment: I am confused why these are JOBs, why aren't you just using a stored procedure. If it is because you want them to run on a schedule, then who provides the different parameters and how? Walk us through a use/best case senerio.
Comment: The property code parameter is "hard-coded" and does not change, neither does the time the package should run (**per property/package**). However, all packages accept the current date/time of the SQL server as parameter. Per your suggestion: how is running a stored procedure on a schedule different than running a package on a schedule?
Comment: You were not clear about the what the "parameter" was. If it is the date, your can use GETDATE() as a parameter which gives you the current date/time. It sounded like it was a parameter that you have to supply everytime, so my question is why is it on a schedule if you have to manually supply a parameter. I know better now. [Using a date as parameter](http://www.dbforums.com/microsoft-sql-server/1645313-how-pass-parameter-values-sql-job-schedule.html)
Comment: Thank you for your help. I am using GETDATE() as one of the parameters. However, my question was whether or not it is a good practice to have 20 jobs set up with their own schedule, instead of 1 job with 20 steps where each step has its own scheduled time to run.
Comment: That was your question? I missed that, sorry. Multple steps allow you to stop execution if a step fails so the thing you do in step 10, will NOT run if step 9 fails. If you care about that requirement, use a sinlge job with multiple steps. If you dont, use multiple jobs.  If you need to control the time of each step, then you must use multiple jobs.  Really, the answer is based on what you need to accomplish.
Comment: I need to control the time a step runs. I was hoping that a step could run at a certain time. Thank you for the clarification. Please answer that and I will accept it as the answer.
Answer: Multiple steps allow you to stop execution if a step fails so the thing you do in step 10, will NOT run if step 9 fails.
If you care about that requirement, use a single job with multiple steps. If you don't, use multiple jobs.
If you need to control the time of each step, then you must use multiple jobs.
Really, the answer is based on what you need to accomplish.
Comment: BTW, you could do a step the will wait for a specified amount of time, but I dont think you want to do that, based on your requirements.
Comment: I ended up building a package schedule table and a watcher. Thank you!


Spring Boot - Alterar nomes de propriedades de um objeto ao retornar JSON da API

Question: Galera boa noite!
Estou com uma api rest criada com spring boot + hibernate e tudo que tem direito!
Vamos imaginar o seguinte cenário: O engenheiro de dados criou o banco na seguinte forma
TB_PESSOA
no_nome
nu_cpf
sg_uf
dt_aniversario

Como vocês fariam para "REMAPEAR" (não sei dar um nome a isso xD) para quando a o recurso da API for exposta exibir da forma natural....
nome
cpf
uf
aniversario

ps: não sei se é possivel "mapear". se alguém tiver uma ideia =)
ps: vou consumir com react, também gostaria de enviar no mesmo padrão (nome,cpf,uf...)
Answer: É possível alterar as propriedades no momento da serialização do objeto.
O que acho importante é destacar que essa transformação está mais relacionada com sua classe do que com o modelo de dados, conforme você exemplificou.
Como você não deu detalhes da sua implementação, vou explicar utilizando a classe Pessoa como exemplo:
import java.util.Date;

import lombok.Data;

@Data
public class Pessoa {
    private String no_nome;
    private String nu_cpf;
    private String sg_uf;
    private Date dt_aniversario;
}

Algumas considerações:

O Spring Boot por padrão pode utilizar Jackson, GSON ou JSON-B para serialização/deserialização de objetos, utilizando seus recursos de auto configuração
Cada framework possui suas características e anotações para customizar o payload de resposta, o ideal é verificar a documentação
Utilizarei como exemplo o framework Jackson

Por padrão o Jackson utiliza o nome da propriedade da classe para serialização, dessa forma a classe pessoa resultará neste JSON:
{
    "no_nome": "NULLPTR",
    "nu_cpf": "00000000191",
    "sg_uf": "PR",
    "dt_aniversario": "1994-01-01"
}

Para alterar este comportamento, utilizamos as anotações do framework de serialização para customizar as propriedades como abaixo:
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;

@Data
public class Pessoa {
    @JsonProperty("nome")
    private String no_nome;
    @JsonProperty("cpf")
    private String nu_cpf;
    @JsonProperty("uf")
    private String sg_uf;
    @JsonProperty("aniversario")
    private Date dt_aniversario;
}

Nessa situação o @JsonProperty está especificando o nome que o campo deve assumir ao ser serializado, resultando no seguinte:
{
    "nome": "NULLPTR",
    "cpf": "00000000191",
    "uf": "PR",
    "aniversario": "1994-01-01"
}

É importante notar que as anotações deixam o código cada vez mais carregado e trás mais complexidade, é comum adotar-se DTOs para retornos de APIs e não utilizar-se diretamente da entidade de banco de dados (onde já discuti sobre isso aqui).
Mas, por serem em momentos distintos, é possível utilizar uma entidade JPA conforme o exemplo abaixo:
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;

@Data
@Entity
@Table(name = "TB_PESSOA")
public class Pessoa {

    @Id
    @JsonIgnore
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name = "no_nome")
    @JsonProperty("nome")
    private String algumNome;

    @Column(name = "nu_cpf")
    @JsonProperty("cpf")
    private String algumCpf;

    @Column(name = "sg_uf")
    @JsonProperty("uf")
    private String algumUf;

    @Column(name = "dt_aniversario")
    @JsonProperty("aniversario")
    private Date umaDataDeAniversario;
}

Durante a serialização essa classe irá produzir o resultado esperado, porém, note que eu já tive que introduzir um @JsonIgnore para não deixar o id do banco de dados aparecer no payload. Isso trás sérios problemas quando seu modelo muda, e o payload de resposta da sua API não deve mudar.
Links:
Docs Spring Boot - Serialização/Deserialização
Anotações Jackson
Entities vs DTOs
Comment: Obrigado por sua resposta meu amigo! Foi de grande aprendizado! já tinha pesquisado sobre DTO! agora sei que estou no caminho certo.!
Comment: Ótimo @Kasio não esquece de aceitar a resposta :)


how to print db_select result using watchdog?

Question: I'm trying to debug below code:
$perishables = db_select('userpoints_txn', 'up_txn')
    ->fields('up_txn', array('txn_id', 'uid', 'points', 'remainder', 'time_stamp', 'tid', 'operation', 'description'))
    ->condition('status', 0, '=')
    ->condition('expired', 0, '=')
    ->condition('expirydate', 0, '!=')
    ->condition('expirydate', REQUEST_TIME, '<')
    ->execute();
 watchdog('userpoints', 'perishables->remainder  %perrr', array('%perrr' =>$perishables), WATCHDOG_DEBUG);

Can anyone help me how to get  $perishables in the report log files?
Answer:
execute(): - this will not return query results to you. All it will return is database connection object and query string. See the screen shot.

In order to get query results, you need to call any of the retrieve function. For example
fetch();        // Use the default fetch mode.
fetchObject();  // Fetch as a stdClass object.
fetchAssoc();   // Fetch as an associative array.
Debugging queries:
I would recommend you to use devel module and its help functions as dpm() and dpq() . They will make your debugging process a lot more faster can clean than watchdog.
watchdog() - I confirm the answer by @Decipher(+1) will record the query object in database, see the scrrenshot tested with a simple query

Might be that log is not something that you want to see, a small change to @Decipher answer if you want to see the query String
watchdog('userpoints', 'perishables->remainder %perrr', array('%perrr' => print_r($perishables->queryString, TRUE)), WATCHDOG_DEBUG);

You can definitely make it better the way you want with above mentioned tools
Comment: Agreed, it's better to use the devel module and dpm() & dpq(), you can run the query and see the results straight away without digging in the logs.
Answer: Use print_r() with the $return argument set as TRUE.
example
watchdog('userpoints', 'perishables->remainder %perrr', array('%perrr' => print_r($perishables, TRUE)), WATCHDOG_DEBUG);

Comment: thank you for the answer.I replaced my watchdog statement,but still  i'm not able to find result  in recent log reports
Comment: My answer was based on the question, you only get results when you fetch them, as mentioned in @arpitr's answer.


how to get current active android app user email from firebase using firebaseAuth

Question: My app have two user( buyer and seller).
I am tring to get current user email which is buyers but when i run the below code, it shows previously logged in user email which is the seller's one.
        String userID= FirebaseAuth.getInstance().getCurrentUser().getEmail();

How to write firebase code to get current active user email.
Comment: Why do you say "it shows previously logged in user email"? Have you successfully signed out?
Comment: A single `FirebaseApp` instance will only have at most one active user. Signing in or creating another user, automatically signs the previous user out. So it sounds like the seller was the last user to sign in.
Answer: When you go to the Auth > Sign-In Methods page of your project in the Firebase console. do you have One account per email address on or off? If you allow multiple accounts per email address, you will get null for FirebaseUser.getEmail()
Answer: Use this code snippet FirebaseAuth.getInstance().signOut(); to sign out the current user properly, after successfully signed out you can repopulate your user model from Firebase Auth/login in new user. Hope your problem will be solved with this.


weird error - failed to open stream - .module file in theme path?

Question: I am just editing empty template, creating regions and so on. After I first time cleared cache weird error started to appear at every cache clearing:

Warning: include_once(C:\xampp\htdocs\hkmzvolen/sites/all/themes/activit/activit.module):
  failed to open stream: No such file or directory v
  _theme_process_registry() (riadok 565 z C:\xampp\htdocs\hkmzvolen\includes\theme.inc).
Warning: include_once(): Failed opening
  'C:\xampp\htdocs\hkmzvolen/sites/all/themes/activit/activit.module'
  for inclusion (include_path='.;C:\xampp\php\PEAR') v
  _theme_process_registry() (riadok 565 z C:\xampp\htdocs\hkmzvolen\includes\theme.inc).

It is trying to include activit.module from theme folder and not from module folder. There are a custom module and custom theme with the same name - activit. But there is no any activit.module file in theme directory nor I am including the file anywhere in my code.
Why is drupal trying to include this nonexisting file from my theme path?
Answer:
There are a custom module and custom theme with the same name - activit

That's what causes the problem. Module and theme names need to be unique amongst one another. Drupal doesn't support duplicate names, and weird things can happen if you go against that.
See Module/theme name collision for more information.


Flag the node after login

Question: I am using flag module to bookmark the content. Authenticated user can normally flag the content. For anonymous user when they click on flag link it should go to login page. After successful login it should flag the node automatically.
I have the code for flagging the content, but I could find how to flag after login.
<code>$flag = flag_get_flag('wishlist');
$flag->flag('flag', $nid, user_load($uid), TRUE);
</code>
Answer: You can try using hook_node_view for doing this.
What it does is:

Act on a node that is being assembled before rendering.

Here is an idea to try out:
<code>/**
 * Implements hook_node_view
 */
function yourmodule_node_view ($node, $view_mode, $langcode) {

  // use a one-timer boolean for this action
  if(user_is_logged_in() && !isset($_SESSION['autoflagging_once']))
  {
    $_SESSION['autoflagging_once'] = true;
    $flag = flag_get_flag('wishlist');
    $flag->flag('flag', $node->nid, user_load($uid), TRUE);
  }

}
</code>
Good luck!

Flag the node after login


How to verify that a function is a pmf of a discrete random variable?

Question: I am preparing for a prob/stats exam and have encountered this practice question:

I am confused about what it means to "verify that $p(x)$ is a pmf of a discrete random variable" for a few reasons:

A pmf, by definition, is a function that gives the probability of a discrete random variable...

It literally shows that the values x can take are discrete.

Do I need to use probability axioms or something? Is there some notational description of a pmf I need to compare this to?
Comment: Hint: a pmf must sum to $1$. (And, of course, its values must be nonnegative.)
Answer: Since this is a discrete random variable you have to verify that $\sum_{x=0}^{\infty} p(x) =1$.
In doing so remember the geometric series $\sum_{x=0}^{\infty} (\frac{1}{4})^x=\frac{4}{3}$.
Similarly, if you had to verify that some function $f$ represented a pdf you would have to show that $\int f(x) dx=1$


Can anyone give me a comprehensive guide to installing tensorflow-federated on M1 Mac?

Question: i followed the instructions given by the official tf documentation, but i just cannot resolve the various problems encountered.
Did anyone have the experience installing tff on m1 mac and can show me your overall process?
conda create -n federated python=3.8

conda activate federated

pip install --upgrade tensorflow_federated

everything seems to be fine according to the terminal output, however,
after
import tensorflow_federated as tff

i got a RunTimeError:
RuntimeError: This version of jaxlib was built using AVX instructions, which your CPU and/or operating system do not support. You may be able work around this issue by building jaxlib from source.

how to resolve this?
Comment: Could you share what error messages you got?
Comment: Please have a look at [this](https://stackoverflow.com/a/68345659/14290681) similar resolved issue to fix this `RuntimeError`.
Comment: How to solve the dependency conflict occurred??
Answer: Install miniforge with Apple's arm64: Apple Silicon Method. Then, put it where Anaconda places its initialization code, that is in ~/zshrc.
This would make miniforge the default manager. Following which you need to create a ~/.start_anaconda.sh script so that Anaconda can be used as an alternative.
With miniforge,

Create a new conda environment mytraxenv with conda create -n mytraxenv python=3 which has your python version.
Activate the environment with conda activate mytraxenv
run conda install numpy and conda install six to ensure numpy.six and wheel in mytraxenv environment.
Then pip install -U pip pip install -U

Lastly follow these instructions to install
pip install --upgrade pip
pip install --upgrade "jax[cpu]"


Incomplete and strange words from serial Arduino to Android

Question: I use the tutorial Data transfer between Android and Arduino via Bluetooth to receive code from Arduino.
I made a textview with the id txtArduino, and I use .append, but why do I get incomplete text when the Arduino sends?
For example:

LED ON, and:w- . iin:13

And similar strange text like this.
How can I fix this problem?
PS: I can provide more code if needed.
Android Header
h = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case RECIEVE_MESSAGE:                                     // If receive massage
                byte[] readBuf = (byte[]) msg.obj;
                String strIncom = new String(readBuf, 0, msg.arg1);   // Create string from bytes array
                sb.append(strIncom);                                  // Append string
                int endOfLineIndex = sb.indexOf("\r\n");              // Determine the end-of-line
                if (endOfLineIndex > 0) {                             // If end-of-line,
                    String sbprint = sb.substring(0, endOfLineIndex); // Extract string
                    sb.delete(0, sb.length());                        // And clear
                    txtArduino.append(sbprint + "\n");                // Update TextView

                    //toggleDOOR.setEnabled(true);
                }
                Log.d(TAG, "...Mesaj:"+ sb.toString() +  " Byte:" + msg.arg1 + "...");
                break;
            }
    };
};

Arduino Code:
int cnt = 0;
int pinLed = 13;

String myKey = "0000001";

//Pin Geam Masina 2 si 3
int pinGeamInchis = 2;
int pinGeamDeschis = 3;

char incomingByte;
void setup(){
    Serial.begin(9600);

    //INITIALIZARE
    pinMode(pinLed,OUTPUT);
    pinMode(pinGeamInchis,OUTPUT);
    pinMode(pinGeamDeschis,OUTPUT);

    digitalWrite(pinLed,LOW);

    Serial.print("Modul ON( KEY:");
    Serial.print(myKey);
    Serial.print(" )\r\n");
}

void loop(){
    if(Serial.available()> 0){
        incomingByte = Serial.read();
        if(incomingByte == '0'){
            //Opreste LED
            digitalWrite(pinLed,LOW);
            Serial.print("Pin 13: LED OFF\r\n");

            //Inchide Geam
            digitalWrite(pinGeamInchis,HIGH);
            Serial.print("Command:W-C\r\n");
            delay(500);
            digitalWrite(pinGeamInchis,LOW);
            Serial.print("Pin 2:Window Down\r\n");
        }
        if(incomingByte == '1'){
            //Aprinde LED
            digitalWrite(pinLed,HIGH);
            Serial.print("LED ON\r\n");

            //Deschide Geam
            digitalWrite(pinGeamDeschis,HIGH);
            Serial.print("Command:W-O\r\n");
            delay(500);
            digitalWrite(pinGeamDeschis,LOW);
            Serial.print("Pin 3:Window Up\r\n");
        }
    }
}

I see, if I send only one "command", it works. What can I do so I can receive more commands at ones on serial and on Android?
PS: I use Arduino Nano.
Comment: 1. Are you sure you are using the correct baud-rate for the BT module? Is it set to comunicate at 9600bps? 2. How is your Arduino clocked? Quartz? At which frequency?
Comment: the module is set to 9600bps
Comment: the idea is that If I use a bluetooth terminal from google play it works with no errors or stuff , I get exactly what I send on serial.
Answer: Analysis
Looking at your Android code:
String sbprint = sb.substring(0, endOfLineIndex); // Extract string
sb.delete(0, sb.length());                        // And clear
txtArduino.append(sbprint + "\n");                // Update TextView

You take the message that was received up to the (first) newline and then delete the whole message. I think, one cannot be sure how much data will be inside any given "message" received.
For instance, when the Arduino does:
Serial.print("Pin 13: LED OFF\r\n");
// [...]
Serial.print("Command:W-C\r\n");

this will be sent to the BT module just the same as:
Serial.print("Pin 13: LED OFF\r\nCommand:W-C\r\n");

And then "someone" (BT module? Android OS? ...?) may decide to put this in two "messages" (or "packets"), for example
Message1: "Pin 13: LED OFF\r\nComm"
Message2: "and:W-C\r\n"

In this case, you would then only see
"Pin 13: LED OFF"

and
"and:W-C"

displayed, because you deleted the "Comm" part of the first message.
Suggestion
Try and replace your sb.delete(0, sb.length()); with sb.delete(0, endOfLineIndex + "\r\n".length());, so that you don't delete the whole string but only the part that is actually displayed and keep the rest to be completed by the next message.
You should then also add a loop to make sure your code will not fail when more than one newline is in a message. For this, simply replace:
int endOfLineIndex = sb.indexOf("\r\n"); // Determine the end-of-line
if (endOfLineIndex > 0) {                // If end-of-line,

with
int endOfLineIndex;
while ( (endOfLineIndex = sb.indexOf("\r\n")) > 0) { // While there's at least one complete line in buffer,

Comment: I did what you suggested I still get strange strings , if I send 199 sometimes I get 999
Answer: Instead of sending print("/r/n") on the Arduino side just put a empty System.println();
Like this:
void taskTransmitData(void)
{
  // start the xml
  Serial.print("HE");
  Serial.print(pMyMemory->currentHeading);
  Serial.print("/HE");

----

  Serial.print("CS");
  Serial.print(currentState);
  Serial.print("/CS");

  Serial.println();

}

On the android side, this should work:
bytes = mmInStream.read(buffer);
byte[] readBuf = (byte[]) buffer;
String strIncom = new String(readBuf, 0, bytes); // create string from bytes array
sb.append(strIncom);      // append string
int endOfLineIndex = sb.indexOf("\r\n");  // determine the end-of-line
if (endOfLineIndex > 0) {
    // add the current string to eol to a local string
    String sbprint = sb.substring(0, endOfLineIndex);

    // get the start and end indexes of the heading
    int startHeading = sb.indexOf("HE");
    int endHeading = sb.indexOf("/HE");

    // set the heading
    Henry.this.setCurrentHeading(sb.substring((startHeading + 2), endHeading));

    ......

    // get the start and end indexes of the current state
    int startCS = sb.indexOf("CS");
    int endCS = sb.indexOf("/CS");

    // set the current state
    Henry.this.currentState = sb.substring((startCS + 2), endCS);

    // output what we have
    //System.out.println("recv: " + sbprint);
    sb.delete(0, sb.length());
}


Laravel retrieve relationship data via another relationship

Question: I have three tables
Question table:
id
title
description

Answer table:
id
answerbody
question_id

Likes table:
id
answer_id

I want to retrieve single question details with all the answers and answer_count and their respective likes (only like_count)
I tried this
public function show($id)
{
    return question::with(['answers','answers.likes'])->withCount(['answers'])->where('id',$id)-
    >get();
}

How do I return likes with count?
Comment: have you defined your relations in your project?
Comment: yes,i have defined the relations.everything working fine.i just need the likes to be count.
Comment: It looks like this answers your question. https://stackoverflow.com/questions/39633691/laravel-5-3-withcount-nested-relation
Comment: Use [counting related model](https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models)
Comment: @AnuratChapanond I tried this-return question::with(['answers'])->withCount(['answers','likes'])->where('id',$id)->get();it throws a error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'likes.question_id'
Comment: @RaffianMoin yes and you have to define likes relationship in the question model using hasManyThrough as suggested in the answer in the link.
Comment: @AnuratChapanond I did this- public function likes()
    {
        return $this->hasManyThrough(answer::class, like::class);
    }
Comment: @RaffianMoin almost there, swap Answer::class and Like::class
Comment: @AnuratChapanond yes mate it worked.but it returns total likes of all the answers.i want like count of individual answers.how do i do that?
Comment: Oh well, you didn't mention it in the question though. I don't know how to do that unfortunately.
Answer: If you need all answers for a question and along with their likes count you can call a closure inside your with() clause  and load their related likes count as
Question::with(['answers'=> function ($query) {
                $query->withCount('likes')
                      ->orderBy('likes_count', 'desc');
        }])
        ->withCount(['answers'])
        ->where('id',$id)
        ->get();

This way you can also sort the answers based on their likes count
Comment: @RaffianMoin If it worked give you your expected result please accept this answer or take a time to go through [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)
Answer: Each question has many answers. So in the Question model add the below code :
public function answer()
    {
        return $this->hasMany(Answer::class);
    }

Each answer has many likes. So in the Answer model add the below code :
public function likes()
    {
        return $this->hasMany(Like::class);
    }

Now you have to define a mutator "getDataAttribute" as below in the Question model:
public function getDataAttribute()
    {
        return [
            'question' => $this,
            'answers' => $this->answers()->get(),
            'answer_count' => $this->answers()->get()->count(),
            'likes' => $this->answers()->likes()->get(),
        ];
    }

Finally, anywhere you needed the question information you just need to invoke :
$question->data

to retrieve question, likes and question count.


Why do I get "An invalid selection has been identified." from the form my code creates?

Question: I am using the following code for a form.
public function buildForm(array $form, FormStateInterface $form_state) {
  $region_options = static::getFirstDropdownOptions();
  $form['vvv_region'] = [
    '#type' => 'select',
    '#title' => $this->t('region select field'),
    '#options' => $region_options,
    '#empty_option' => t('- Select region -'),
    '#ajax' => [
      'callback' => '::myAjaxCallback',
      'disable-refocus' => FALSE,
      'event' => 'change',
      'wrapper' => 'edit-output',
      'progress' => [
        'type' => 'throbber',
        'message' => $this->t('Verifying entry...'),
      ],
    ]
  ];

  $region_selected = $form_state->getValue('vvv_region');
  $city_options = static::getSecondDropdownOptions($region_selected);

  $form['output'] = [
    '#type' => 'select',
    '#title' => $this->t('city select field'),
    '#options' => $city_options,
    '#prefix' => '
',
    '#suffix' => '
',
    '#empty_option' => t('- Select city -'),
    '#default_value' => '',
    '#ajax' => [
      'callback' => '::cityAjaxCallback',
      'disable-refocus' => FALSE,
      'event' => 'change',
      'wrapper' => 'edit-city',
      'progress' => [
        'type' => 'throbber',
        'message' => $this->t('Verifying entry...'),
      ],
    ]
  ];

  $city_select = $form_state->getValue('output');
  $suburb_options = static::getSuburbDropdownOptions($city_select);

  $form['sur'] = [
    '#type' => 'select',
    '#options' => $suburb_options,
    '#prefix' => '
',
    '#suffix' => '
',
    '#empty_option' => t('- Select sururb -'),
    '#default_value' => array(''),
  ];
  return $form;
}

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $region_selected = $form_state->getValue('vvv_region');
  $city_options = static::getSecondDropdownOptions($region_selected);

  if ($form_state->getErrors()) {
    \Drupal::messenger()->addError($region_selected);
    $form_state->setRebuild();
  }

  $form['outpout']['#options'] = $city_options;

  return $form['output'];
}

public function cityAjaxCallback(array &$form, FormStateInterface $form_state) {
  $city_select = $form_state->getValue('output');
  $sur_data = static::getSuburbDropdownOptions($city_select);

  if ($form_state->getErrors()) {
    \Drupal::messenger()->addError($city_select);
    $form_state->setRebuild();
  }

  $form['sur']['#options'] = $sur_data;

  return $form['sur'];
}

When the form is submitted, I get the following error.

An invalid selection has been identified. Please contact the site administrator.

What's wrong with the code I am using?
Comment: You can't change the value of the options in the ajax callback. It must be done in the form definition. You can read an example of how to do that in this tutorial I wrote: https://www.jaypan.com/tutorial/drupal-form-api-ajax-form-and-results-same-page
Comment: There is a typo in the first callback: `$form['outpout']['#options'] = $city_options;`. It should be *output*, not *outpout*.
Answer: There are two errors in the code shown in the question.
It's only the form builder that can add options to form elements. Differently, you will get the error you quoted.

An invalid selection has been identified. Please contact the site administrator.

What the AJAX callback does is simply returning the form element that needs to be changed. In your case, the code is the following one.
public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['output'];
}

public function cityAjaxCallback(array &$form, FormStateInterface $form_state) {
  return $form['sur'];
}

AN AJAX callback for a form doesn't usually handle validation errors.
The second error is in the form builder, which uses the following code.
$region_selected = $form_state->getValue('vvv_region');

When the form is first built, $form_state->getValue('vvv_region') doesn't return any value, as the form isn't yet submitted, even via AJAX. It's only when the form is submitted via AJAX that $form_state->getValue('vvv_region') returns a value. That line needs to be changed as follows.
$region_selected = $form_state->hasValue('vvv_region') ? $form_state->getValue('vvv_region') : key($region_options);

Similarly, $city_select = $form_state->getValue('output'); needs to be changed.
$city_select = $form_state->hasValue('output') ? $form_state->getValue('output'): key($city_options);


Cannot access data passed to $vars in theme function

Question: I have got a problem in my template.php file, where I am trying to add data to $vars. I basically have a preprocess function for a view and in it I am trying to pass some extra info to $vars. However, the view is not getting those variables. This is what I have in my template.php file:
/**
  * Generic preprocess that is still working on D7
  */
function mytheme_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;
    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
* preprocess variables for the badge owners view
*/
//function mytheme_preprocess_views_view__badge_owners (&$vars) {
function mytheme_preprocess_views_view_fields__badge_owners__page_1(&$vars) {
  $bid = $vars['view']->args[0];

  //Get the badge info
  $badge = db_query("
    SELECT ubb.bid, ubb.weight, ubb.name, ubb.image, ubb.href,
    ubb.unhideable, ubb.fixedweight, ubb.doesnotcounttolimit, ubb.tid
    FROM {user_badges_badges} ubb
    WHERE ubb.bid = :bid", array(
      ':bid' => $bid
  ))->fetchObject();

  $vars['bid'] = $bid;
  $vars['name'] = $badge->name;
  $vars['badge'] = theme('user_badge', array('badge' => $badge));
  $vars['an_extra_variable'] = 'hope this shows up in $vars';

  drupal_set_title(t('Badge: @badge_name', array('@badge_name' => $badge->name)));
}

This is what I have in my views-view--badge-owners.tpl.php file:
<?php
/**
* Variables available:
* - $css_name: A css-safe version of the view name.
* - $header: The view header
* - $footer: The view footer
* - $rows: The results of the view query, if any
* - $empty: The empty text to display if the view is empty
* - $pager: The pager next/prev links to display, if any
* - $exposed: Exposed widget form/info to display
* - $feed_icon: Feed icon to display, if any
* - $more: A link to view more, if any
* - $admin_links: A rendered list of administrative links
* - $admin_links_raw: A list of administrative links suitable for theme('links')
*
* @ingroup views_templates
*/
?>
<div class="view view-<?php print $css_name; ?> view-id-<?php print $name; ?> view-display-id-<?php print $display_id; ?> view-dom-id-<?php print $dom_id; ?>">
  <?php if (isset($admin_links)): ?>

      <?php print $admin_links; ?>

  <?php endif; ?>

<?php print $badge;?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

  <?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

 <?php /* class view */ ?>

Any help would be appreciated. Thanks.
Comment: Have you tried assigning the `$badge` vars as an array on `$vars['view']` instead? e.g `$vars['view']->badge = $badge_info_array;`
Answer: OK, it looks as though you're using the $badge variables in a more general parent/container views template, when the $badge variables are added in a child template preprocess function. The tpl variables aren't available at that container point.
The solution is to implement
hook_preprocess_views_view
and add the badge data vars there instead.
e.g
THEMENAME_preprocess_views_view(&$vars){
  if (isset($vars['view']->name)) {
    switch($vars['view']->name){
      case 'badge_owners':
        if($vars['view']->current_display == 'page_1'){
          // Rename current function to this
          THEMENAME_preprocess_views_view_badge_owners_page_1($vars);
        }
      break;
    }
  }
}

Comment: Awesome!!!! Thanks, that worked like a charm!  Saved me 2 days of work!
Comment: Thanks, that is excellent, it is working now!  But there is one tiny problem still, setting the title of the view.  For some reason, this line is not working: drupal_set_title(t('Badge: @badge_name', array('@badge_name' => $badge->name)));  Any thoughts?
Comment: Glad to hear it!, regarding setting the page title, perhaps you can use `$vars['view']->set_title($title);` there instead? Otherwise may need some way to get the title to hook_preprocess_page


How to make group visible, but content hidden?

Question: Using Organic Groups, I'd like to have three visibility states:

Group and group content is visible to all, including anonymous users.
Authenticated users can see the group, but not the content.

This would be the same thing as if everyone marked all the content as "private", but the group node was marked as "public."

Only members of the group can see the group and the group content.

I tried OG Visibility, but it is no longer maintained and did not work. Or at least I couldn't figure out how to get it to work.
Any suggestions?
This is on Drupal 7.
Answer: Steps:

Go to Configuration > Organic groups > OG field settings
Under Bundle, select your group content type
Under Fields, select Group visibility and click Add field
Under Fields again, select Group content visibility and click Add field

Now these settings will add two fields into your group node which are Group visibility(Public or Private) and Group content visibility(Public or Private).
If I understood your comment requirements right, to achieve requirement:

No. 1 - Set group visibility to public and content visibility to public
No. 2 - Set group visibility to public and content visibility to private
No. 3 - Set group visibility to private and content visibility to private
Comment: That is pretty much what I'm doing now. What missing is that I want Public, Private, and Hidden as options where we currently have just Public and Private. That way users can just leave the visibility setting at the default when they create content.
Comment: Awesome! Hidden? How about using the node status as published or unpublished for it?
Comment: Hidden still needs to be visible to anyone in the group. Not sure how well using unpublished would work. Plus, my main goal is to make this really obvious to end users. That's why I'd like the three different options in the same place. I wonder if I should fork og_visibility...
Comment: So, OG Visibility decided to start working for me. Not sure why it wasn't working before. Plus, it's been a while since it started working... In any case, this answer is pretty much what people should do, so I'm checking it.


É possível obter o usuário do firebase pelo UID?

Question: A duvida consiste no seguinte problema:
Estou com um projeto utilizando firebase e ionic 3.
Estou utilizando o modo de autenticação via E-mail, na qual tem o e-mail e o UID armazenados.
Por exemplo:
Tenho 2 usuários cadastrados na base.
1_ firstname.lastname@example.com UID = 123
2_ firstname.lastname@example.com UID = 321
No meu código eu tenho um elemento mensagem que possui o id de quem está enviando, por exemplo:
Mensagem 1 = descricao: "descricao", idUsuario: "123"
Estou logado com o usuário de UID 321 e quero recuperar o usuário de UID 123 para exibir o e-mail dele, como faço isso?
Eu não queria armazenar no database do firebase, mas como nao tem outra maneira, então, alguém saberia me informar como faço para criar uma tela de cadastro que cadastra via email/senha e que armazena no firebase esses dados.
PS: estou tentando utilizando autenticação via token do usuário logado para escrever no database, mas para realizar o cadastro não há nenhum token, por isso não estou conseguindo.
Esta assim:
 return this.http
  .post(this.urlDataBase + email + '/user.json?auth=' + token, usuario)
  .map((response: Response) => {
    console.log(response);
    return response.json();
  });

Mas não está salvando no firebase, está dando erro 400:
Response {_body: "{↵  "error" : "Invalid path: Invalid token in path"↵}↵", status: 400, ok: false, statusText: "Bad Request", headers: Headers, …}

Comment: Os dados da sua mensagem estão armazenados no Data Base Real Time do firebase?? quando vc salva não pode colocar logo o e-mail não?
Comment: segundo esta resposta não e possível: https://stackoverflow.com/questions/14673708/how-do-i-return-a-list-of-users-if-i-use-the-firebase-simple-username-password
Comment: Só utilizando o authentication não é possível. Você terá de utilizar a database
Comment: Obrigado.
Sacanagem não ter um meio de acessar esses dados...
Answer: Conforme dito no Link, não é possível fazer essa leitura do Firebase diretamente, mas existem algumas outras formas de se fazer as validações para que possa ser realizado operações de CRUD diretamente no firebase.
When using email / password authentication in Firebase Authentication (previously known as Firebase SimpleLogin), your user's email and password combination is securely stored separately from the data actually stored in your Firebase.
This barrier between the data in your Firebase and your users' email / password hash combinations is by design: we want to make it easier for you to (1) develop your application, (2) prevent any accidental user credential leaks, and (3) still give you total flexibility with how to store your user data in Firebase.
*That means that we only store the email address / password hash combination and nothing else, so it is up to you to decide how to store actual user data in your Firebase. *
GOOGLE TRANSLATE - TRADUÇÃO
Ao usar a autenticação de e-mail / senha no Firebase Authentication (anteriormente conhecido como Firebase SimpleLogin), a combinação de e-mail e senha do usuário é armazenada de maneira segura separadamente dos dados armazenados no Firebase.
Essa barreira entre os dados em seu Firebase e as combinações de hash de senha / email dos usuários é por design: queremos facilitar para você (1) desenvolver seu aplicativo, (2) evitar qualquer vazamento acidental de credenciais do usuário e (3) ainda oferece flexibilidade total sobre como armazenar seus dados de usuário no Firebase.
Isso significa que apenas armazenamos a combinação de hash de endereço de e-mail / senha e nada mais. Por isso, cabe a você decidir como armazenar dados reais do usuário no seu Firebase.

Bem você pode pegar o ID do usuário e armazenar esses dados no seu Firebase em um local como /users/$id e usar o Firebase Security Rules Language para determinar o acesso de leitura / gravação a esses dados. O ID e o email exclusivos de seus usuários já estão na variável auth que você usará ao redigir as regras.
Outra alternativa é

A aplicação entrar com um acesso "Admin" (apenas de Leitura e/ou escrita [depende das necessidades])
Pegar uma lista de usuários do Firebase
Utilizar a lista para fazer as validações necessárias

Desse modo você estaria logado e poderá fazer as operações de criação de usuário, atualização de dados, apagar um usuário, ler usuários etc.
Answer: Eu passei pelo mesmo problema. Não existe outro jeito a não ser armazenar o UID + informações deste usuário dentro do Firestore/Real DataBase.
O Firestore Authentication na verdade é um serviço isolado de autenticação de usuário, assim como o Cognito da AWS onde informações de acesso são guardadas dentro desse serviço.
Buscando um pouco, percebi que eu deveria armazenar dentro de uma Collection "User" os dados do usuário (nome, sobrenome, email, cidade...) e também o UID como chave (id).
O fluxo foi basicamente :
1) O usuário faz o registro na aplicação
2) O Firestore Authentication gera um novo autenticado
3) Automaticamente eu crio um novo DOC dentro da Collection "User" tendo o ID idêntico ao UID gerado dentro do FA.
Dentro do fórum oficial do Firestore eu encontrei muitas pessoas falando que isso não seria "incorreto", pois o UID do usuário não oferece nenhuma possibilidade de acesso aos dados sensíveis e também não é um.


Run two scripts in separate directories, in parallel, and in foreground

Question: Context: I'm trying to write a bash function to make my life incrementally more convenient, but I don't think the goal is possible. I'm hoping I can get someone to Confirm/Deny my suspicion:
Goal/Question: Make a shell function that will start a rails server in one directory and start up react in another, but without opening two terminal tabs and running the commands separately. (Is this possible?)
Attempted:
function run_project(){
  (cd [RAILS_PROJ_DIR] && exec rails server) && (cd [REACT_PROJ_DIR] && exec yarn start)
}

Issues: Function doesn't work because the second command waits for the first to finish successfully. But if I can somehow get both to run successfully, wouldn't one run in the background (which prevents me from viewing log output)?
UPDATE:
Thanks for responses, all.  I got close to what I wanted with a little modification, but it's a bit of a square peg solution for a round hole:
function run_project(){
(cd [RAILS_PROJ_DIR] && exec rails server &) && (cd [REACT_PROJ_DIR] && exec yarn start &)
}
As others have pointed out, mixing both log outputs isn't ideal, and this also seems to prevent pry from working.  Foreman is probably the real way to go.  Marking as accepted answer.
Comment: There is only one "foreground". You can't run two processes in the foreground. Of course you could run two processes in the background, and writing a special "collector" program which would grab the output of those processes and displays it in some interleaved way - but isn't this going to be confusing? Maybe something like [multitail](https://linux.die.net/man/1/multitail) would better suit your requirements.
Comment: Would you still like to read both the logs together?
Answer: You can start commands in the background via shell by using an '&'.
(cd /some/directory; ./command1 -a arg) >output.txt 2>&1 &
(cd /some/other/directory; ./command2 -a other_arg) >output2.txt 2>&1 &

That will capture the output for each command to a file which you can then use 'tail -f' to keep an eye on.
Note that if you logout before the commands complete, they may get killed.  If you want to prevent that behavior use the 'nohup' command when you launch them.
Once the commands are running, use the 'jobs' command to see them listed at which point you can bring either one to the foreground using the 'fg' command.  While the command is in the foreground, use ^Z to stop it and then type 'bg' to send it to the background.
Not exactly what you're looking for but you cannot have two jobs in the foreground at the same time. You can, however, switch between them using basic job control commands.
Jamess-MacBook:bin jj$ (while [ 1 ]; do echo 'job 1'; sleep 3; done) >/tmp/job1.out 2>&1 &
[1] 3735
Jamess-MacBook:bin jj$ (while [ 1 ]; do echo 'job 2'; sleep 3; done) >/tmp/job2.out 2>&1 &
[2] 3740
Jamess-MacBook:bin jj$ tail -f /tmp/job
job1.out  job2.out
Jamess-MacBook:bin jj$ tail -f /tmp/job?.out

==> /tmp/job1.out <==
job 1
job 1
job 1
job 1
job 1
job 1
job 1

==> /tmp/job2.out <==
job 2
job 2
job 2
job 2

==> /tmp/job1.out <==
job 1
^C
Jamess-MacBook:bin jj$ jobs
[1]-  Running                 ( while [ 1 ]; do
    echo 'job 1'; sleep 3;
done ) > /tmp/job1.out 2>&1 &
[2]+  Running                 ( while [ 1 ]; do
    echo 'job 2'; sleep 3;
done ) > /tmp/job2.out 2>&1 &
Jamess-MacBook:bin jj$ fg %1
( while [ 1 ]; do
    echo 'job 1'; sleep 3;
done ) > /tmp/job1.out 2>&1
^Z
[1]+  Stopped                 ( while [ 1 ]; do
echo 'job 1'; sleep 3;
done ) > /tmp/job1.out 2>&1
Jamess-MacBook:bin jj$ bg
[1]+ ( while [ 1 ]; do
    echo 'job 1'; sleep 3;
done ) > /tmp/job1.out 2>&1 &
Jamess-MacBook:bin jj$
Jamess-MacBook:bin jj$ jobs
[1]-  Running                 ( while [ 1 ]; do
    echo 'job 1'; sleep 3;
done ) > /tmp/job1.out 2>&1 &
[2]+  Running                 ( while [ 1 ]; do
    echo 'job 2'; sleep 3;
done ) > /tmp/job2.out 2>&1 &
Jamess-MacBook:bin jj$ kill %1
Jamess-MacBook:bin jj$ kill %2
[1]-  Terminated: 15          ( while [ 1 ]; do
    echo 'job 1'; sleep 3;
done ) > /tmp/job1.out 2>&1
Jamess-MacBook:bin jj$ jobs
[2]+  Terminated: 15          ( while [ 1 ]; do
    echo 'job 2'; sleep 3;
done ) > /tmp/job2.out 2>&1
Jamess-MacBook:bin jj$ jobs
Jamess-MacBook:bin jj$

Answer: I believe what you're looking for is something like Foreman:
https://github.com/ddollar/foreman
http://blog.daviddollar.org/2011/05/06/introducing-foreman.html
You can list all your commands in using a Procfile like so:
Procfile.dev:
web: bundle exec rails server
yarn: exec yarn start

And then simply run foreman start in your command line.
Answer: Replace the second && with &.
Indeed, the command to the left of & will run in background but you will be able to see its output, albeit intermixed with the other command's output.


Run application on any user sign in/log on with elevated privileges

Question: I am trying to make an application run on any user sign in (or session connection, be it local or remote) having elevated privileges, but without UAC prompt. When new user is added, application should run on his sign ins as well, without additional setup.
I have setup Hyper-V machine with Windows 10 Enterprise v.1709 for testing purposes. On it I have main (referenced as "Admin") account, which is in Administrators group, and one (referenced as "User") account which is only in Users group.
I have created simple WPF application which shows current user and whether it has admin privileges. Final application will be WPF as well.
I will be using WiX to create installer for my application suite (aforementioned application, windows service, maybe something more). The behavior from the title must be set automatically during installation. On installation I can do whatever I want, being limited only by WiX capabilities, but it allows me to run custom application (C#) during setup, so I think there are no restrictions. Installation will be run from account with admin privileges.
Below is what I have tried and what was the outcome:
App in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

"Run this program as an Administrator" not checked
Admin: Starts, no admin privileges
User: Starts, no admin privileges
"Run this program as an Administrator" checked for all users
Admin: Does not start
User: Does not start

Entry in HKLM\Software\Microsoft\Windows\CurrentVersion\Run

"Run this program as an Administrator" not checked
Admin: Starts, no admin privileges
User: Starts, no admin privileges
"Run this program as an Administrator" checked for all users
Admin: Does not start
User: Does not start

Task Scheduler, trigger "At log on of any user"

No other options
Admin: Does not start
User: Does not start
"Run with highest privileges" checked
Admin: Starts, admin privileges
User: Does not start
"Run this program as an Administrator" checked for all users
Admin: Does not start
User: Does not start
"Run this program as an Administrator" checked for all users, "Run with highest privileges" checked
Admin: Starts, admin privileges
User: Does not start

How can it be done? Event Viewer seems to not log any specific information when application does not run at all. Should it be there or such logs might be placed somewhere else? Where then?
Target: Windows 8+, Server 2012+
Comment: What does your app do that it needs admin rights and needs to run in the context of the user with admin rights?
Comment: 1. Application must see current user identity as it sends some data with user's login. 2. Application must access and be able to modify registry under HKLM; Second restriction was made so the overall architecture would be simpler - no WCF or any other communication on the machine. The other way would be to have registry per user (HKCU), but some settings are to be shared. Is there elegant way to do this? Shared db-like file, maybe sqlite? Having such solution would remove admin privileges constraint and the application could work as normal user app.
Comment: See my edited answer.
Answer: If you must have a GUI, then the correct way to handle this is to have a GUI app and a separate system service. The service does the actual work, and the GUI just passes commands to it. Impersonation can be used to allow the service to act as the user.

If the only reason you need admin access is to write to an HKLM key, then admin access is the wrong way to do this. In your installer, create the registry key and change the ACL on the key so that Users have Write access. No admin rights needed to run the app that way.
Comment: Thanks! After some fight with ACL, I managed to access registry without admin privileges :)
Comment: This doesn't really solve the initial question
Comment: @Bluscream The simple answer is it's not possible. And then I gave functionally equivalent solutions. How does this not solve the initial question?