Equivalence of definitions of tangent space

Question: For a given manifold $M$ and a point $x \in M$, we can define the tangent space at $x$, $T_xM$ in two ways (more, actually, but I am just concerned about these two for now):
1) Given a chart $(U, \phi)$, where $p \in U$, call two curves
$\gamma_1 : (-1,1) \to M $, $ \gamma_2 : (-1,1) \to M $, ($ \gamma_1(0)=\gamma_2(0)=p$)
$\textbf{equivalent}$ if
$ (\phi \circ \gamma_1)'(0)=(\phi \circ \gamma_2)'(0)$.
Call the equivalence classes $[\gamma]$ the $\textbf{tangent vectors of }$M$ \textbf{ at } x$. Define $T_xM$ as the collection of $[\gamma]$'s. These classes map to vectors in $\mathbb{R}^n$ via $[\gamma] \mapsto \frac{d}{dt}(\phi \circ \gamma)(0)$.
2) A $\textbf{derivation at } x$ is a linear map $D_x:C^\infty(M) \to \mathbb{R}$ such that, $\forall f,g \in C^\infty(M)$,
$D_x(fg)=D_x(f)g(x)+D_x(g)f(x)$.
Call the vector space of all derviations at $x$ the tangent space at $x$, $T_xM$.

I understand that, given a $[\gamma]$, we can get a derivation $D_\gamma$ given by
$D_\gamma(f) := \frac{d}{dt}(f \circ \gamma)(0)$.
I am unclear as to how to go the other direction; given a derivation $D$, how can I get an equivalence class $[\gamma]$ of curves?
Thanks!
Comment: The other direction is considerably harder. In fact, it is not true for $C^k$ manifolds with $k<\infty$, only for smooth manifolds. A detailed proof may be found in *Foundations of Differential Manifolds and Lie Groups* by Frank Warner.
Answer: Let $D$ be a derivation at $p$. Take local coordinates $(x^1, \dots, x^n)$ at $p$, with $p$ mapping to $0$. The goal is to show that $D$ can be written in these coordinates as
$$
   D = \sum_i c^i \frac{\partial}{\partial x^i} \tag{$*$}
$$
for some constants $c^i$; having done this you can take your path to be the line whose coordinate representation is
$$
  t \mapsto t(c^1, \dots, c^n).
$$
This gives a representative of the equivalence class you want.
For this to have a chance of being true, it's clear that $c^i$ must be the value $D(x^i)$ of the derivation on the smooth function $x^i$. Here's how this is proved:
We use the following lemma from calculus: If $f$ is a smooth function on a neighborhood $U$ of $0$ in $\mathbb{R}^n$ with $f(0) = 0$, then there exist smooth functions $g_i$ on $U$ such that $f(x) = \sum_i x^i g_i(x)$, and such that $g_i(0) = \tfrac{\partial f}{\partial x^i} (0)$. This lemma isn't hard to prove; one just writes
$$
  f(x) = \int_0^1 \frac{\partial}{\partial t} \Big( f(tx) \Big) dt
$$
and uses the chain rule.
Now, note that the action of $D$ on $f$ is equal to the action of $D$ on $f - f(p)$, since $D$ is linear and $D(1) = 0$, and so it suffices to check $(*)$ for functions $f$ with $f(p) = 0$.
Let $f$ be such a function. Using the lemma, and noting that the $x^i$ are themselves smooth functions on $U$,
$$
  D(f) = \sum D(x^i g_i) = \sum D(x^i) g_i(p) = \sum D(x^i) \frac{\partial f}{\partial x^i} (p),
$$
which establishes $(*)$ for $c^i = D(x^i)$. (The middle equality is just the Leibniz rule, using the fact that $x^i(p) = 0$.)
Comment: How can I show that the curve "$t \mapsto t(c^1, \dots, c^n)$" is in $M$ ? ( In your text , 6 line)
Comment: That curve, call it $\tau$, maps to $\mathbb{R}^n$, _not_ $M$. If our chosen local coordinates are given by the chart $\phi:U\rightarrow \phi(U)$ for an nbd $U\ni p$, then we can make the curve map to $M$ by simply considering $\phi^{-1}\circ\tau$. Note that since $\phi(U)\subset \mathbb{R}^n$ contains an open ball centered at $\phi(p)$, we can always modify $\phi$ by scaling appropriately by $\lambda_I$ (i.e., replace $\phi$ with $\tilde{\phi}(x)=\lambda_I \phi(x)$) to ensure $\tau(I)\subseteq \phi(M)$ (where $I=(-1,1)$, or whatever interval you want), so that the composition is well-defined.


batch file is not being executed from scheduled task

Question: I have batch file that need to run every day at 9 AM and create log.
batch file works fine manually (by clicking it or from command line).
However, When i set up the task by using task scheduler, it fails to run. (cmd.exe quickly shows up and shuts down and task is complete. (@ task scheduler log)
However, no log has been created.
I also tried putting pause in my program to hope that my program is being executed, but sadly it isn't.
Can anyone tell me what is the solution to this? Thanks in advance.
Comment: Is it set to run regardless if the user is logged in?  Also, like MDMarra mentioned,  verify which user the task is running under.  This greatly impacts the ability of the task to run successfully.  What happens if you run the task manually from the GUI?
Answer: By default, scheduled tasks run as SYSTEM. It sounds like SYSTEM doesn't have permission to create the file in the specified location.
You can use psexec -s yourScript.bat to manually run a batch file as SYSTEM to test this with. You can grab the latest version of psexec here.
Answer: Specify the Start In location.
Comment: I know this answer is old, but this fixed my issue. I'm not sure if because my batch script is on a different drive (E:) had anything to do with it. Thanks! +1


When did the oboe wind up being the standard to tune other instruments in an ensemble / orchestra?

Question: As a follow up to the question why does the orchestra tune to the oboe, I'm asking since when this became standard practice?  For example, was it since the Modern oboe, or already since the Classical oboe used in Mozart time?  Did Bach use the Baroque oboe to tune his orchestra?
If not (any kind of) the oboe, which instruments have been used to fulfill this function?  Comments have identified: cello (which in turn is tuned by a chamber/continuo organ), clarinet, etc.
Comment: I don't know that it's historical, but I can speak to common practice in early-music ensembles *today*. That keyboard "continuo" instrument, be it portative organ or harpsichord, is joined in its role by low strings, esp. the cello. So, since the organ/harpsichord is too quiet for the whole ensemble to hear well, the cello first takes the pitches C, G, D, and A from the keyboard (one at a time, because temperament). It then plays them for the other low strings, then G, D, A for violins (and then the violone and violins take an E directly from the keyboard, or tune it by ear to neighboring
Comment: Part of the problem is, throughout the baroque period and into the classical, there usually *was* a keyboard instrument present in pretty much any setting that would also have an oboe.
Comment: strings), and then the cello gives a pitch to whatever winds might be present (typically an A, or maybe a D depending on key).
Comment: @AndyBonner Who knows [this style of portative organ](https://www.youtube.com/watch?v=Wb8z9lXRcKI) was the one commonly used to tune the cello?  It looks portable enough and dated back to the medieval period.  [Another demo with 21st century composition](https://www.youtube.com/watch?v=Uk4iVold0eU).
Comment: I was speaking of the baroque period; that's a medieval hand-organ. Here's a video of what I had in mind, with our tuning procedure as well (though you can't see or hear much). You get some better shots of the organ once we start playing. So "portative" in the sense that it's not built into a building, but still something that takes two people to lift. https://www.youtube.com/live/sZb8f8mbwzA?si=i8x6Z0s2y91DAXk4&t=1854
Comment: Interestingly (or not :-) ),  Concert Bands, aka Wind Ensembles usually tune to the clarinet even though there are oboes in the group.
Comment: I'm too lazy/busy to find a copy in the library so as to get more than the Google Books preview, but the definitive answer appears to lie in pp 375 ff of https://www.google.com/books/edition/The_Birth_of_the_Orchestra/YT6LlQoeL8MC?hl=en&gbpv=1&dq=tuning&pg=PA375&printsec=frontcover. Looks like "not standardized to the oboe until the 19th century" is a safe answer.
Comment: @AndyBonner Thanks, will look into it.  Re: "portative" organ, I was imagining a scenario where a "box / chamber/ positive organ" was *not* being used in the performance and therefor *not* available in the room (instead the continuo instrument was a harpsichord or a lute).  I wonder whether in that scenario they took the trouble to bring in that medieval portative organ as the "tuning fork" only (since tuning fork was not invented until 1711), simply because of its portability and legacy.  Or maybe the cellist go to another room to tune it first?
Comment: I doubt anyone would bother to bring in any instrument that wasn't going to perform, solely as a tuning source (aside from tuning fork or pitch pipe). Also, organs really aren't a great stable reference! They have to warm up, and do go out of tune. Meanwhile, it might be necessary to delimit this question to "when did oboe wind up being standard," and not "what was the full history of ensemble tuning before that," because it was very heterogeneous.
Comment: @AndyBonner Thanks for the feedback, esp 1) the book reference which is most instructive to broaden tuning practice more than simply a matter of selecting the primary instrument (it mentions "preluding", for instance, even buying practice (!) for wind instruments and requiring the players to transpose a semitone or more) and 2) describing the current practice with cello without oboe.  Sometimes my wild imagination gets the better of me.  I hope the question is better now.
Answer: For baroque music you tend to have a preference for smaller ensembles (which is not to say that no large scale works exist), and you often to have a keyboard instrument (harpsichord or organ). It takes significant time to tune a harpsichord, and a lot more time to tune an organ. This means that usually you'd tune after the keyboard instruments, and with ensembles my experience is that people would tune after the cello (which tunes after the harpsichord). With larger ensembles you naturally get the problem that you need a lot of space, and this naturally means it is hard to hear a single instrument. The oboe naturally offers itself for this, as its high harmonic content makes the sound carry well, and due to coupling at the reed the overtones are harmonic.
So I suppose that with larger ensembles this would have been established quite quickly (though I do not know the exact history of this).


Enviar objeto com lista de objetos do android para SOAP web service em C#, utilizando ksoap2

Question: Eu envio um objeto contendo uma lista de objetos, o web service reconhece o objeto mas não reconhece a lista.
Esse é o código fonte:
public RetornoDto GravarRecebimentoNf (NotaFiscal nf, int codFilial, String nummatricula) throws Exception {
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    SoapObject RelacaoDetalhePedido =  new SoapObject("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "RelacaoDetalhePedido");

    for(int i = 0; i < nf.getItens().size(); i++){

         SoapObject RelacaoImeiProduto = new SoapObject(NAMESPACE, "RelacaoImeiProduto");

        for(int j = 0; j < nf.getItens().get(i).getListDetalheImeiPedidoDescentralizadoDto().size(); j++){

            SoapObject DetalheImeiPedidoDescentralizadoDto = new SoapObject(NAMESPACE, "DetalheImeiPedidoDescentralizadoDto");

            DetalheImeiPedidoDescentralizadoDto.addProperty("Sequencial", nf.getItens().get(i).getListDetalheImeiPedidoDescentralizadoDto().get(j).getSequencial());

            SoapObject RelacaoImei = new SoapObject(NAMESPACE, "RelacaoImei");
            for(String imei : nf.getItens().get(i).getListDetalheImeiPedidoDescentralizadoDto().get(j).getRelacaoImei()){
                RelacaoImei.addProperty("string", imei);
            }
            DetalheImeiPedidoDescentralizadoDto.addProperty("RelacaoImei", RelacaoImei);

            RelacaoImeiProduto.addProperty("DetalheImeiPedidoDescentralizadoDto", DetalheImeiPedidoDescentralizadoDto);
        }

        SoapObject DetalhePedidoDescentralizadoDto = new SoapObject(NAMESPACE, "DetalhePedidoDescentralizadoDto");

        DetalhePedidoDescentralizadoDto.addProperty("CodigoSap", nf.getItens().get(i).getCodSap());
        DetalhePedidoDescentralizadoDto.addProperty("QuantidadaRecebida",nf.getItens().get(i).getQtd());
        DetalhePedidoDescentralizadoDto.addProperty("UnidadeComercializacao",
                nf.getItens().get(i).getNomUnidadeComercializacao().equals("anyType{}") ? "" : nf.getItens().get(i).getNomUnidadeComercializacao());
        DetalhePedidoDescentralizadoDto.addProperty("ValorUnitario", String.valueOf(nf.getItens().get(i).getValUnitario()));
        DetalhePedidoDescentralizadoDto.addProperty("ValorTotalBruto",String.valueOf(nf.getItens().get(i).getValTotalBruto()));
        DetalhePedidoDescentralizadoDto.addProperty("Cfop",
                nf.getItens().get(i).getNumCfop().equals("anyType{}") ? "" : nf.getItens().get(i).getNumCfop());
        DetalhePedidoDescentralizadoDto.addProperty("NumeroContrato",nf.getItens().get(i).getNumContrato());
        DetalhePedidoDescentralizadoDto.addProperty("SequencialItemContrato",nf.getItens().get(i).getNumSequencialItemContrato());
        DetalhePedidoDescentralizadoDto.addProperty("ValorCusto",String.valueOf(nf.getItens().get(i).getValCusto()));
        DetalhePedidoDescentralizadoDto.addProperty("QuantidadeMovimentacao",nf.getItens().get(i).getQtdMovimentacao());
        DetalhePedidoDescentralizadoDto.addProperty("QuantidadeAuditada",nf.getItens().get(i).getQtdRecebido());

        DetalhePedidoDescentralizadoDto.addProperty("SequencialItem", nf.getItens().get(i).getNumSequencialItem());

        RelacaoDetalhePedido.addProperty("DetalhePedidoDescentralizadoDto", DetalhePedidoDescentralizadoDto);

    }

    SoapObject pedidoDescentralizado = new SoapObject(NAMESPACE, "pedidoDescentralizado");

    pedidoDescentralizado.addProperty("CodigoFilial", codFilial);
    pedidoDescentralizado.addProperty("ChaveNFe", nf.getNumNotaFiscal().toString());
    pedidoDescentralizado.addProperty("NomeUsuario", nummatricula);

    pedidoDescentralizado.addProperty("RelacaoDetalhePedido", RelacaoDetalhePedido);

    pedidoDescentralizado.addProperty("ValorTotalBaseCalculo", String.valueOf(nf.getValTotalBaseCalculo()));
    pedidoDescentralizado.addProperty("NumeroFatura",
            nf.getNumFatura().equals("anyType{}") ? "" : nf.getNumFatura());
    pedidoDescentralizado.addProperty("ValorOriginalFatura", String.valueOf(nf.getValOriginalFatura()));
    pedidoDescentralizado.addProperty("ValorLiquidoFatura", String.valueOf(nf.getValLiquidoFatura()));

    try{

        SoapObject reqGravarNfe = new SoapObject(NAMESPACE, METHOD_GRAVAR_RECEBIMENTO_NF);
        reqGravarNfe.addProperty("pedidoDescentralizado", pedidoDescentralizado);

        SoapSerializationEnvelope envelopeGravarNfe =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelopeGravarNfe.implicitTypes = true;
        envelopeGravarNfe.dotNet = false;
        envelopeGravarNfe.setOutputSoapObject(reqGravarNfe);

        androidHttpTransport.debug = true;

        androidHttpTransport.call(SOAP_ACTION_GRAVAR_RECEBIMENTO_NF, envelopeGravarNfe);

        Log.d("XML_REQUEST", androidHttpTransport.requestDump);
        Log.d("XML_RESPONSE", androidHttpTransport.responseDump);

        if(envelopeGravarNfe.bodyIn instanceof SoapFault){
            Log.e(WS.class.toString(), ((SoapFault) envelopeGravarNfe.bodyIn).getStackTrace().toString());
            throw new Exception(((SoapFault) envelopeGravarNfe.bodyIn).getMessage());
        }

        SoapObject objSoap = (SoapObject) envelopeGravarNfe.bodyIn;

        SoapObject objSoapNfe = (SoapObject) objSoap.getProperty(0);

        RetornoDto retorno = new RetornoDto();

        retorno.setContemErro(Boolean.parseBoolean(objSoapNfe.getPropertySafely("ContemErro", false).toString()));
        retorno.setMensagemErro(objSoapNfe.getPropertySafely("MensagemErro", "").toString());
        retorno.setCodigoBarrasInexistente(objSoapNfe.getPropertySafely("CodigoBarrasInexistente", "").toString());

        return retorno;
    }catch (Exception e){
        e.printStackTrace();
        throw e;
    }
}

Esse é o XML request
<v:Envelope
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns:d="http://www.w3.org/2001/XMLSchema"
xmlns:c="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
<v:Body>
    <n0:GravarRecebimentoPedidoDescentralizado id="o0" c:root="1"
        xmlns:n0="http://tempuri.org/">
        <pedidoDescentralizado>
            <CodigoFilial>309</CodigoFilial>
            <ChaveNFe>32190304904042000450550010002008301677770271</ChaveNFe>
            <NomeUsuario>943665</NomeUsuario>
            <RelacaoDetalhePedido>
                <DetalhePedidoDescentralizadoDto>
                    <CodigoSap>000000000000157309</CodigoSap>
                    <QuantidadaRecebida>20</QuantidadaRecebida>
                    <UnidadeComercializacao></UnidadeComercializacao>
                    <ValorUnitario>0.0</ValorUnitario>
                    <ValorTotalBruto>0.0</ValorTotalBruto>
                    <Cfop></Cfop>
                    <NumeroContrato>7500002424</NumeroContrato>
                    <SequencialItemContrato>00500</SequencialItemContrato>
                    <ValorCusto>690.0</ValorCusto>
                    <QuantidadeMovimentacao>0</QuantidadeMovimentacao>
                    <QuantidadeAuditada>1</QuantidadeAuditada>
                    <SequencialItem>20</SequencialItem>
                </DetalhePedidoDescentralizadoDto>
            </RelacaoDetalhePedido>
            <ValorTotalBaseCalculo>0.0</ValorTotalBaseCalculo>
            <NumeroFatura></NumeroFatura>
            <ValorOriginalFatura>0.0</ValorOriginalFatura>
            <ValorLiquidoFatura>0.0</ValorLiquidoFatura>
        </pedidoDescentralizado>
    </n0:GravarRecebimentoPedidoDescentralizado>
</v:Body></v:Envelope>

E aqui o web service recebendo o objeto com a lista nula

Alguém já passou por isso ou conhece alguma solução?
Parece um problema comum, mas não encontrei resposta no fórum.
Answer: Resolvi da seguinte forma:
envelopeGravarNfe.dotNet = true;

E criando um PropertyInfo para cada atributo, com seu respectivo NAMESPACE.
pedidoDescentralizado.addProperty(newProperty("ValorLiquidoFatura", NAMESPACE_DOMAIN, String.valueOf(nf.getValLiquidoFatura())));

...
private PropertyInfo newProperty(String name, String namespace, Object value){
    PropertyInfo propertyInfo = new PropertyInfo();

    propertyInfo.setName(name);
    propertyInfo.setValue(value);
    propertyInfo.setNamespace(namespace);

    return propertyInfo;
}


How do I find the exact solution to the boundary value problem $y''(x) = −xy' (x) + y(x) − 1$, $y(0) = 1$, $y(4) = 9$?

Question: I believe I need to guess a general solution of $y$ for this boundary value problem. However I am not sure what that guess is. Can someone explain if I am on the right track or not? If so what is the guess for the general solution of y?
Answer: We try $y = ax+b$. Substitute into the original equation, we get $b=1$. It happens to fit the first boundary condition. The second boundary condition gives $a=2$. Since the boundary condition uniquely determines this equation, this above solution is the unique one.
For a more general setting $y''(x) = −xy' (x) + y(x) − \beta$, $\beta\ne 1$, the above trial solution ceases to work. But after differentiating the equation once, we have
$$y'''=-xy''.$$
It is a first order ODE of $y''$. Solve,
$$\frac{y''(x)}{y''(x_0)}=\exp\bigg(-\frac{x^2-x_0^2}{2}\bigg),$$
for some $x_0$ where $y''(x_0)\ne 0$. $x_0$ exists. Otherwise $y$ is reduced to the linear form that fails to satisfy the equation.
You can integrate and match the boundary condition to arrive at the solution.
Comment: Yes, it is an educated guess. It is hard to classify "what form does the differential equation have to be in" for the linear form to work. I get the trial solution only by assuming the left hand side to be zero for all $x$. It is also a byproduct of excluding the special case in the general solution in the second paragraph. It just happens that the constant term on the right hand side is $-1$ which matches the boundary condition $y(0)=1$. Otherwise, it does not work. I mention that at the beginning of the second paragraph. Please refer to the second paragraph for the general solution.
Comment: How do you get $y′′′=−xy′′$ when you differentiate the equation?
Comment: Have you tried differentiating the expressions on both sides of the equation?
Comment: yes. I don see how you get your result. Also i do not understand how it helps. Can you elaborate please?
Comment: What do you get differentiating the right hand side of the original equation?
Comment: I have added the (unique) solution for this particular equation in the first paragraph. You can skip the general solution from the second paragraph down, so the question of differentiating the equation becomes moot.
Comment: Thanks I understand your first paragraph. Am I right in saying that $y=ax +b$ is an educated guess for the form of the unique solution? If so what form does the differential equation have to be in for $y=ax +b$ to be a suitable educated guess?


A problem on analytic function on $\mathbb C-\{ 0 \}$

Question: Let f be an analytic function in $\mathbb C-\{ 0 \}$ such that $f(1/{n\pi})$=sin $({n\pi})$ for all $n\in \mathbb Z$. Is f(z)=sin(1/z) for all $z\in \mathbb C-\{0\}$ ?
Take g(z)=sin(1/z) and set $S =\{z\in \mathbb C:(f-g)(z)=0\}$ .The set S contain $\{1/{n\pi}:n \in \mathbb Z\}$ whose limit point does not in $\mathbb C-\{ 0 \}$, further i can't proceed.what is the result?Someone help.Thanks in advance.
Comment: What about $f(z)=e^z\sin(1/z)$?
Answer: Hint: Consider $h(z) = z \sin \left( \frac{1}{z} \right)$.


How do I assess the capacity of my link for Active Directory needs?

Question: I'm working for a company that has a head office and some remote sites. We have an Active Directory server in the head office and we now want all of the users in the remote sites to join and work on the domain at the head office.
I want to assess our bandwidth to see if we have enough to carry all the traffic between offices smoothly. What can I do or which tool can I use for the assessment and statistics?
Comment: Belongs on ServerFault
Comment: Performing a real life test on your network will often reveal the most information.
Answer: Without knowing what services your providing beyond authentication (such as group policy, file/print sharing, etc), This is what I would do.
Live test/Slow rollout

Start with your remote sites, one by one, establish a link back to hq, most likely via vpn.
Join your workstations to the domain. Make sure the users can access the necessary resources in the process (file/print sharing, group policy is working, etc.)
Keep an eye on the bandwidth at the remote office as well as at hq. Everyone has their own opinion about this, but If I see bandwidth utilization consistently above %75 throughout business hours then I would be looking to upgrade the link at that location if it's in the budget. Peaks above this are fine, and to be expected. As for the tools to use for this, it depends on what you're using along to route your traffic. PFSense for example has a built in traffic graphs that will show you how saturated the link is.

I'm sure other business grade routers have similar tools. If you're looking for latency, tools such as SmokePing can help you monitor latency from the remote office to hq.
Lastly, as mentioned above, it's a constant process of monitoring the network, both at the remote site and at hq, because as the needs of remote offices grow, so will there bandwidth requirements. To curve this, if some offices are big enough, it may be worth it to setup domain controllers and/or other servers on site. This has the advantage of having only that server talk back to hq, preserving a lot of bandwidth in the process, when using technology such as BITS, which MS pushes these days.
Comment: As BigHomie stated, this task really cannot be completed without knowing what services and traffic will need to flow over the link. Most small offices should have no trouble at all. If you do find that you need to limit traffic, start by building a domain controller at each site and then investigate using BranchCache (and/or DFS) to minimize bandwidth used by file shares.
Answer: If they are only using it for word documents and AD authentication, the workload will probably be quite low - but there are a lot of other things to consider such as:
Will their web traffic be sharing the same line?  How about email?  How many computers/users?
There isn't really a way to reliably estimate the traffic you intend to create.
Also, have you considered the possibility of installing an RODC and DFS box at the remote site to lower the load on your network WAN links?
Hope this helps
Answer: I run a network with several remote offices connected by site-to-site VPNs over cable/DSL lines.
If you are just worried about active directory traffic - it's very minimal.  Pretty much negligible.  File shares are a completely different story, and that's going to depend entirely on what people are doing with their files.
We have a few small offices (3-10 people) where there are no servers, everything is saved on the file servers at our head office, where we have fibre and plenty of speed.  This works quite well as long as their internet is reliable.  Do keep in mind that you are limited to the slowest speed in both directions - if you have 5mbit down/1mbit up cable at both locations, you're pretty much limited to 1mbit speeds - since one side will always be sending, and the other side receiving.
For larger offices we install a server on site which functions as domain controller and file server.  This allows them to do some work even if their internet goes down.  Backups are done overnight to our head office when nobody needs the internet.
This works fairly well.  We have run into a few issues - people trying to save music and videos to their network drives for example (which was in some cases actually work related).
The only thing you can really do is try it.  Start with the smallest (in terms of staff) office, and monitor their bandwidth usage.  If things work fine, and staff aren't complaining too much, move on to the next biggest one.  When you do start getting complaints, increase bandwidth or try adding a domain controller/file server at that site and things should improve.  They don't need to be brand new servers - we upgraded ones that really needed it, and took the old ones to the remote offices.


Qual a diferença entre Encoding, Encryption e Hashing?

Question: Gostaria de entender a diferença entre Encoding, Encryption e Hashing e também exemplos de quando se usa um ou outro.
Answer:
Definição simplista

Encoding: é a maneira com que os conjuntos de caracteres são mapeados e manipulados.
Encryption: é o processo de ser criptograr um dado (dado qualquer).
Hashing: é o processo de se gerar uma sequencia de bits baseados em um dado de entrada afim de identifica-lo unicamente.

Definição

Encoding: é a maneira com que os conjuntos de caracteres são mapeados e manipulados pelas máquinas, seja um software, seja um browser etc ex: No encoding ISO 8859-1 a letra "A" está na posição 65º (começando do zero) e pode ser representado no computador usando um único byte com valor de 65.
Encryption: é o processo de transformar informação usando um algoritmo de modo a impossibilitar a sua leitura a todos excepto aqueles que possuam uma informação particular, geralmente referida como chave. O resultado deste processo é informação encriptada.
Hashing: é o processo de se criar um hash que é uma sequência de bits geradas por um algoritmo de dispersão, em geral representada em base hexadecimal, representando um nibble cada. Essa sequência busca identificar um arquivo ou informação unicamente. Por exemplo, uma mensagem de correio eletrônico, uma senha, uma chave criptográfica ou mesmo um arquivo.

Exemplos

Encoding:

UTF-8: é um tipo de codificação Unicode de comprimento variável criado por Ken Thompson e Rob Pike. Pode representar qualquer carácter universal padrão do Unicode, sendo também compatível com o ASCII. Por esta razão, está lentamente a ser adaptado como tipo de codificação padrão para email, páginas web, e outros locais onde os caracteres são armazenados.
ISO 8859-1: é uma codificação de caracteres do alfabeto latino, a primeira parte da ISO 8859. Foi desenvolvida pela ISO, e posteriormente passou a ser mantida pela ISO e pela IEC.

Encryption:

DES: Fundamentalmente DES realiza somente duas operações sobre sua entrada: deslocamento de bits e substituição de bits. A chave controla exatamente como esse processo ocorre. Ao fazer estas operações repetidas vezes e de uma maneira não-linear, chega-se a um resultado que não pode ser revertido a entrada original sem o uso da chave.
IDEA: é um algoritmo de cifra de bloco que faz uso de chaves de 128 bits e que tem uma estrutura semelhante ao DES. Sua implementação em software é mais fácil do que a implementação deste último. Como uma cifra de bloco, também é simétrica. O algoritmo foi concebido como um substituto para o Data Encryption Standard (DES). IDEA é uma pequena revisão de uma cifra anterior, PES (Proposta Encryption Standard); idéia era originalmente chamado IPES (Improved PES).
RC4: é o algoritmo simétrico de criptografia de fluxo mais usado no software e utilizado nos protocolos mais conhecidos, como Secure Socket Layers (SSL) (para proteger o tráfego Internet) e WEP (para a segurança de redes sem fios). RC4 não é considerado um dos melhores sistemas criptográficos pelos adeptos da criptografia, e em algumas aplicações podem converter-se em sistemas muito inseguros.
Blowfish: é uma cifra simétrica de blocos que pode ser usado em substituição ao DES ou IDEA. Ele toma uma chave de tamanho variável, de 32 a 448 bits, tornando-o ideal para aplicações tanto domésticas, quanto comerciais.

Hashing:

MD5: é um algoritmo de hash de 128 bits unidirecional desenvolvido
pela RSA Data Security, Inc., descrito na RFC 1321, e muito utilizado
por softwares com protocolo ponto-a-ponto (P2P, ou Peer-to-Peer, em
inglês) na verificação de integridade de arquivos e logins.
SHA: A família de SHA (Secure Hash Algorithm) está relacionada com as funções criptográficas (message digest). A função mais usada nesta família, a SHA-1, é usada numa grande variedade de aplicações e protocolos de segurança, incluindo TLS, SSL, PGP, SSH, S/MIME e IPSec. SHA-1 foi considerado o sucessor do MD5. Ambos têm vulnerabilidades comprovadas.

Fontes do próprio SOpt:
Tag criptografia
Tag hash
Tag character-encoding
Como fazer hash de senhas de forma segura?
Comment: Então por definição, quando dizemos "encriptar a senha em md5" estamos errados. correto?
Comment: Sim, md5 é um algoritmo de geração de hashes, que podem ser usados para serem `message digest` de uma mensagem que pode ou não estar criptgrafada, ou para outros fins, um hash jamais volta ser o objeto que o originou diferente de um dado cifrado.
Answer: Encoding, às vezes chamado de "serialização", é pegar alguma informação (ex.: um conjunto de caracteres) e representá-la ("codificá-la") por meio de uma sequência de símbolos (ex.: um array de bytes). Normalmente quando se fala em encoding se está referindo a character encoding ("codificação de caracteres"), que é como textos abstratos (sequências de Unicode Code Points) são expressos em bytes (seja pra transporte, seja para tratamento interno).
Encryption (encriptação, cifragem) consiste em transformar uma informação legível em outra ilegível ("indecifrável") por todos exceto aquele que possui um segredo capaz de decifrá-la (chamado de "chave"). A informação encriptada pode ser transformada de volta na informação original, seja com a mesma chave usada para encriptar (criptografia simétrica, ex.: AES, 3DES) ou com uma chave distinta (criptografia assimétrica, ex.: RSA, ECC).
Hashing ("função de embaralhamento criptográfico") é o processo de converter um dado de tamanho arbitrário em um dado de tamanho fixo, de forma que seja impraticável: a) descobrir o dado original a partir do dado hasehado (resistência a pré-imagem); b) dado um hash e sua origem, encontrar dados diferentes do mesmo que produzam o mesmo hash (resistência à segunda pré-imagem); c) produzir com facilidade dados diferentes que produzam o mesmo hash (resistência a colisão).
A principal diferença entre encryption e hashing é que o primeiro processo é reversível e o segundo não é. Os usos de funções de hash incluem:

Identificar unicamente um arquivo, como apontado na resposta do Ricardo Henrique:

Se o hash é resistente a colisões, pode-se usar essa função para rapidamente descobrir se dois arquivos quaisquer dentro de um conjunto maior são iguais (ex.: você tem uma pasta com 50.000 arquivos do mesmo tamanho e quer saber quais estão duplicados; em vez de compará-los todos dois a dois, você hasheia todos e verifica quais têm o hash igual).
Se o hash é resistente à segunda pré-imagem, e o hash de um arquivo é conhecido, então não se pode [facilmente] produzir outro que possua o mesmo hash, de modo que isso pode ser usado para garantir a integridade do arquivo.

Mais, se você usou uma chave criptográfica em conjunto com o hash, além da integridade pode-se garantir a autenticidade do arquivo. Ver HMAC.

Provar que um certo dado é idêntico a outro, sem a necessidade de armazenar esse dado. Muito usado no armazenamento de senhas: se seu BD só contém hashes [resistentes à pré-imagem], um atacante que veja uma cópia do mesmo não consegue descobrir a senha original. E quando um usuário quer se autenticar com o site, este pode recriar o hash da senha e comparar ambos os hashes para ver se coincidem. Se coincidirem, então é muito provável que a senha seja idêntica àquela cadastrada pelo usuário.

Note que conhecer somente o hash não ajuda o atacante em nada - pois o que é usado como credencial de autenticação não é o hash, e sim algo que após hasehado seja igual àquele hash. Enquanto o atacante não encontrar esse "algo", ele não pode personificar aquele usuário.

Um exemplo em que todos os três são usados seria: eu tenho um texto na memória do computador, e quero salvar em um arquivo que só eu consiga acessar. Primeiro eu codifico esse texto em UTF-8, depois eu encripto os bytes resultantes usando uma chave que só eu conheça (derivada de uma senha, por exemplo, ou salva em algum lugar seguro, como um dispositivo removível) e por fim eu hasheio os bytes encriptados de modo que quando eu for decriptar esse arquivo no futuro eu possa ter certeza de que ninguém mexeu nele (o hash também tem de ser salvo num lugar seguro, pra eu comparar com o hash do arquivo no futuro, mas não importa o tamanho do arquivo o hash só terá uns poucos bytes).
Comment: Como eu gosto de respostas assim, são mais fluidas e coloquiais. Evita aquele desgaste ao ler um texto totalmente técnico. Parabéns, se o salário de professor fosse bom, recomendaria que você pensasse em ser um.


Javascript reload the page with hash value

Question: I am trying to refresh the page with this statement in external javascript file after some processes.
window.location.href = window.location.href

It perfectly reload the page but I want to scroll to the specific location after reload.
So, I put this on the page.

And change the javascript to
window.location.href = window.location.href + "#mypara";

This code doesn't reload/refresh the page either
window.location.hash = "#uploadImgSection";
window.location.href = window.location.href;

When I do that, it doesn't reload the page at all. Is there any way I can reload the page with scroll bar position?
Comment: how are you calling `window.location.href`? if you are doing that on page load and you are hitting f5 and you are using firefox (or other browser that scrolls where you were before the f5 on refresh) this _might_ be the problem
Comment: Use a PHP file to redirect to the new page?
Comment: No just html page. The purpose is refresh the page after running some javascript functions and scroll it back to that paragraph's position.
Answer: window.location.href += "#mypara";
location.reload();

First add the hash, then reload the page. The hash will remain there, and the page gets reloaded.
Tested, works.

ps: If a hash already exist in the URL, you may want to directly change it via location.hash instead of .href.
Comment: One other thing. It did refresh the page but it includes post data after the reload. How can I clean those? Those post data are preventing me to delete the data row.
Comment: Well, I had to use query string at last. "window.location.href = url + "&action=reload";". Check action query string in javascripot on page load event, and do this "window.location.hash = "#uploadImgSection";". It's not the way it should work but I had to this way to make this work for now.
Comment: Please read this. http://stackoverflow.com/questions/2405117/difference-between-window-location-href-window-location-href-and-window-location  It does include those POST data which is preventing me to do other postback events.
Comment: Well, I don't know much about POST. You can ask a new question about it though, if you want to.
Comment: Yup Genius in our midst :) Best solution
Comment: Maybe this worked in 2012, but today this forces a full reload rather than using cache.  That's only supposed to happen if you call reload(true), but Firefox at least is just doing a full reload, which is definitely not what you want to happen.
Comment: @GlennMaynard That's probably because you had you devtools opened. According to the HTML spec it should not do a full reload, but it does depend on the browser vendor.
Comment: Doesn't work when the content upon the anchor grows on reload - it navigates to the position where the anchor used to be before the reload, not to where it actually is.
Comment: This doesn't work if the hash value is not modified (i.e. you reload expecting the browser to return to the same anchor). It will return to the previous _scroll position_.
Answer: I wanted to update this question because I found that using window.location.href += "#mypara" will keep appending the parameter to the url even if it exists. I have found the better way is to use
window.location.hash = "#mypara"
location.reload();

Answer: This is really an old post, I would still try and answer with right combination of answers.

location.reload() and location.reload(true) works like F5 on browser. This will post all the form data back to the server if previously load had done it.
location.href will not refresh the page until there is a URL change recognized by the browser. change in hash (#paramname) doesn't qualify for URL change and hence just doing
location.href+="#paramname" will not work.

So, location.href+="?anything#paramname" should reload the page as a new request as ?anything is change in the URL.
Comment: Another one: location.href+='&rand='+Math.rand()+'#myhash';
Comment: Johan, Math.rand() should be changed to Math.random()
Comment: The closest answer (maybe the other answers were correct in 2012, but they're all wrong in 2018), but it has the problem of adding entries to the user's address bar history, which isn't good if you were just trying to refresh the same history state...
Comment: Nice answer. Here is a cooked version:
window.location='&rand='+((new Date()).getTime()%1000000000)+'#myhash';
Comment: IMO this answers the question the best compared to the other posts. It requires no change to the underlying code that may have been written as part of a library for example.
Comment: This is a great answer because the key to understanding this behavior of URLs is in it: "... change in hash (#paramname) doesn't qualify for URL change ". Does anybody have a good reference which explains why this is so?
Comment: awesome answer,  so far the only thing which worked for me
Answer: var loc = location.hash;
location.hash = " ";
location.hash = loc;

Comment: Code-only answers are not very useful.  What is this doing? Why does it work?
Answer: Try this
           var urlString=window.location.href;
           var url=urlString.split("#")[0];
           window.location.href = url + "#mypara";

Comment: This doesn't reload the page at all either.
Comment: "Try this" code only answers aren't very useful.  What's it doing? Why does it work?
Answer: This worked for me:
var tabValue = document.URL;
window.location = tabValue.substring(0, tabValue.lastIndexOf("#"));
window.location.hash = "#tabs-3"; //Whatever is your hash value
location.reload();

Answer: This worked for me
$('body').on('click', '.className', function () {
    var data = $(this).attr('href');
    alert(data);
    window.location.reload();
});

Comment: This seems to basically be a longer way of doing what other answers already do, plus I don't think it includes the #myPara part so won't work like the original poster wants it to, although please edit the answer to clarify that if I'm wrong.
Answer: This work for me
window.location.href = baseUrl + "#/m/team";
 location.reload();


AS3 BitmapData to byteArray

Question: I am trying to serialize a Bitmap to store in an XML file. My plan is to turn the BitmapData into a byteArray, but I haven't been able to fine an example of this.
Other suggestions are also welcome.
Comment: What about base64 encoding the image data?  Why do you want to include the image data in an XML file to begin with?
Answer: The process should be: BitmapData > ByteArray > Base64 > XML
Use the BitmapData getPixels() method to get a ByteArray of the pixels.
Then you can use something like Hurlant's Base64 encoder to convert it to base 64.
Then going the other way, "unbase64" it, then use BitmapData's setPixels to load it.
Comment: +1. Although it was not mentioned in the question, I wouldn't store the raw pixels. PNG would be a good fit here if the image data is going to be compressed and decompressed back and forth (using PNGEncoder from adobe as 3 lib for compressing and Loader.loadBytes for decompressing).

AS3 BitmapData to byteArray


Tell router to make traffic only over one special ip address

Question: I have two routers.
A - is connected to the internet
B - is connected to A router's network
A has some clients (notebooks, computers, printers, etc.).
B has also some clients.
B clients are not allowed to see the clients inside A router's network but should be able to use A network to access the internet.
I am new at routing, networking etc. - how can I tell router B to communicate only with router A and don't show the A network clients?
Router B has DD-WRT installed.
More informations about the networks:
Network A: - router IP (static): 192.168.0.1/24 - DHCP enabled / Linksys WRT54GL (original firmware)
Network B: - router IP (static): 192.168.2.1/24 - DHCP enabled / TP-Link WR1043ND (with DD-WRT v24)
Comment: I know at least 3 solutions, but you need to give more details about e.g. the actual addressing. The easiest would be to statically configure B to add a /32 route to A and set it as default gateway, but this is not 100% fullproof if A routes blindly.
Comment: @BatchyX I added more informations to my question.
Answer: If router B is in NAT mode, you should be able to get by with just a couple firewall rules like so:
<code>iptables -A FORWARD -s 192,168.2.0/24 -d 192.168.0.1 -j ACCEPT
iptables -A FORWARD -d 192.168.0.0/24 -j DROP
</code>
Where to put them in your firewall config depends on what rules you already have. You want them before the other ACCEPT rules except for any RELATED,ESTABLISHED-style conntrack rules.
Comment: The solution is (tested and working):

Install on the ROUTER inside the **green network** the newest DD-WRT version.

After installing DD-WRT go into the Web-Admin-GUI of the **green network** router, to add **ONE** command line.

Inside the Web-Admin-GUI goto:
"Administration" --> "Commands" and add this line:

`iptables -I FORWARD -d 192.168.0.0/24 -j DROP` *(192.168.0.0/24 is the network number of the **orange network**)*

**IMPORTANT:** that the router don't forget this line at reboot - save it with the button "Save Firewall".


Mascara moeda com jquery

Question: eu preciso de uma marca para um campo com valor , estou usando o jquery.maskinput
funciona perfeito mas eu tenho que digitar o valor inteiro!
oque estou procurando é uma mascara que preencha automático " R$ $var.000,00 "
por exemplo, se eu tiver um valor de 500mil , com maskinput eu teria que digita
50000000
mas com a mascara que eu citei acima so teria que digitar
500
alguem tem alguma dica sobre isso??
Answer: Sem fazer qualquer validação, apenas para conseguir o que você citou.

$('input').on('keyup', function() {

var v = $(this).val();

if (parseInt(v.length) === 3) {

$(this).val((v * 1000).toLocaleString('pt-br', {style: 'currency', currency: 'BRL'}));

}

});

<input type="text" />
Comment: eu agradeço a resposta rapida, entao os valores deste input varia muito, entre 50mil ate 4milhoes  , entao teria que ser um tipo de mascara onde acompanha o valor, o que vc passou funcionou mas so com valores entre 100mil a 999mil
Answer: Existe um plugin jQuery que talvez possa ajudar, se chama jquery-maskmoney, segue o link:
http://plentz.github.io/jquery-maskmoney/
Comment: tentei utilizar o maskmaney mas n consegui editar para deixar como eu quero :(

Mascara moeda com jquery


Limit tends to infinity $\lim_{x \to \infty}\sqrt{x^2+x}+2\sqrt{x^2+2x}-x$

Question: $\lim_{x \to \infty}\sqrt{x^2+x}+2\sqrt{x^2+2x}-x$
I tried multiply the conjugate and can't work out. Please advise
Answer: It blows up: the first term is larger than $x$, and the second is larger than $2x$, so the whole thing is larger than $3x-x=2x$. (The lesson here is not to get so bound up in technique that you forget to think about what's actually going on!)
Comment: @Peter: $$\huge\text{B}\infty\text{M}$$
Comment: $$\text{- It blows up...}$$
$$\text{- Take cover!}$$
Comment: Yeah, thanks. I guess the either the textbook is wrong or my memory failed. I wonder if this exists at first, but I remembered the answer was -3/2, so.
Comment: @Paul: You're welcome. My guess is that either there was a typo in the problem, or you misremembered it.


Proving given sets are mathematical intervals

Question: Let's assume we have a subset of real numbers called $S$. We call the set of upper bounds of $S$, $U$ and we call its set of lower bounds, $L$.
If we define a set called $G$ that consists of any real number not included in the sets $S$, $U$ and $L$, how could we prove that $U$, $L$ and especially, $S \cup G$ are all mathematical intervals?
Comment: Hint. $S\cup G\subseteq [a,b]$ for $a\in L$ and $b\in U$.
Answer: You use the definition.  That is, to prove $X$ is an interval, suppose $a,b \in X$ and $a < c < b.$  Then show $c \in X.$
For $L,$ show that $c < b$ and $b \in L$ implies $c \in L.$
$U$ is similar to $L.$
For $S \cup G,$ show that $c < b$ and $b \in S \cup G$ implies $c \not\in U.$   Similarly, $a < c$ and $a \in S \cup G$ implies $c \not\in L.$  Conclude $c \in S \cup G.$


theming user profile with "User Field Privacy" - but no "Privacy" available

Question: My setup is like this: multiple additional user fields (not using profile2) and the module "User Field Privacy" is enabled.
I am currently theming user profile pages through a preprocess function and the corresponding  user-profile.tpl.php… Now I have some fields that should be visible to some roles, but hidden to others. I trigger this through the module  "User Field Privacy". Looking for variables in the devel dump does not bring anything for "User Field Privacy" .
<code> [field_telefon] => Array
         (
           [und] => Array
              (
                [0] => Array
                   (
                     [value] => +01 234 567 890
                     [format] =>
                     [safe_value] => +01 234 567 890
                    )

               )

          )
</code>
When not theming through preprocess and .tpl, everything is fine – the fields marked hidden are actually hidden from regular and anonymous users, but shown to users with the appropriate permission.
How/where can I find the "marker" or "flag" for the User Field Privacy setting ?
Any pointers, hints and tips welcome!
Answer: update/solved: I did solve my problem now with very basic measurements: for each field I wanted to have a 'privat option' for, I added an extra checkbox field ("public/private"). This setup just works fine no need to have "User Field Privacy" installed – at least for me. Hope this might help somebody some day.


Request time out error

Question: Hi Today i came across strange problem whenever i try to pinging to my server works properly but whenever i send http request from browser the request time out happens.
can anybody help me to resolve this issue.
Answer: Can you telnet to port 80 on your server?
telnet <server_host_or_ip_address> 80

If not, is the server listening on port 80?
netstat -lntp | grep :80

If not is your webserver daemon running?
Apache for instance
ps auxw | grep [h]ttpd

If your webserver daemon is running and listening on port 80 but you still cannot connect it's probably a firewall rule.
Answer: The server responding to a ping means that it received an ICMP packet, and transmitted a response.  That is ALL that ping means.  It has nothing to do with the HTTP protocol on port 80.  It sounds like the server is up, but the web service on the machine is down / broken.

Request time out error


ProGuard Obfuscate Error, plobleme with my Dao?

Question: I try to obfuscated my apk, but i have a problem with Dao.Image Problem Here Second Image Problem Here, here below its my code, for de proguard-rules, why class i need to keep?
<code>-useuniqueclassmembernames
-dontusemixedcaseclassnames
-dontoptimize
-dontshrink

-keepparameternames

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application

-keepclasseswithmembernames class * {
native <methods>;
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}

-keep class my.dao.package.*$Properties {
public static <fields>;
}

-keepclassmembers class my.dao.package.** {
public java.lang.String TABLENAME;
}
</code>
Comment: added your full error  it is not clear in picture
Answer: I solve my question like this...
// The 'xxx' its my packageName where i put my dao's
<code>-keep class xxx.dao.**{*;}
</code>
Apparently there are ploblems with my Dao class, i not Obfuscate this class.


Solving $\dot{x}-\dot{y}+a(x-y)+b(x\dot{y}-y\dot{x})=0$.

Question: Let us consider the following differential equation
$$\dot{x}-\dot{y}+a(x-y)+b(x\dot{y}-y\dot{x})=0\, .$$
What can we say about the functions $x(t)$, $y(t)$ that solve this equation? Can we find a relation between them, $f(x(t),y(t))=0$? For example, I tried substituting $w=x-y$; I obtained the folowing:
$$a\, w(t)\int \frac{1}{w(t)}dt=1-b \, x(t)\, .$$
I don't think that it is possible to do better. Or not?
Answer: This may be a stupid answer.
Why not to consider $y(x)$ leading to the differential equation
$$1-y'+a(x-y)+b(x{y'}-y)=0$$ that is to say
$$(bx-1)y'-(a+b)y+ax+1=0$$ which leads to $$y=x+c_1 (b x-1)^{\frac{a+b}{b}}$$
Answer: Assuming $b \neq  0$, the equation can be written as the determinant
$$\left|\begin{array}{cc}{x'}+\frac{a}{b}&1-b x\\
{y'}+\frac{a}{b}&1-b y
\end{array}\right| = 0$$
Let $u = \binom{x}{y}$ and $v = \binom{1}{1}$, there is
a function $k(t)$ such that
$${u'} = -\frac{a}{b} v+k \left(v-b u\right)$$
This is now a simple first order linear system.
Comment: I forgot to assume $b \neq 0$. Just out of curiosity, because of your user name, are you in France ?
Comment: @ClaudeLeibovici This is a confidential piece of information!
Comment: Thank you all! Is $k$ unknown? There is not a way to determine it, right?
Comment: $k$ can be any arbitrary continuous function, if you suppose for example that $x, y$ have continuous derivatives. Note that the point $(1/b, 1/b)$ should be studied separately because the equation vanishes at that point. I would be tempted to use $(\phi, \psi) = (1 - b x, 1 - b y)$ because the equation becomes simply $\binom{\phi}{\psi}^\prime = a \binom{1}{1} + k \binom{\phi}{\psi}$.


How a statically-allocated variable-size array works in C++ ?

Question: #include <iostream>

    using namespace std;

    int main(int argc, const char * argv[])
    {

        int size;
        cin >> size;
        int myArray[size]; //this shouldn't compile , right ?

        return 0;
    }

I thought this wouldn't compile, but it does actually (using the g++ command).
What I found out later is that GCC actually allows variable-size arrays even if by standard C++ doesn't support variable-size arrays, Which is weird ! Because I hear everyone saying that the only way to create a variable-size array is to use dynamic allocation like int* array = new int[size]; or better std::vector. I thought GCC wouldn't allow that piece of code !
Anyway, My theoretical question is, the myArray array is allocated in the heap or stack area ?
Comment: You're a bit too late: http://stackoverflow.com/questions/12484588/differences-with-ide-compilers-array-handling. Your answer is in the linked post there as well.
Comment: @DavidRodríguez-dribeas, It's explained in the question linked to from my link, though. Quoting the accepted answer, *gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap allocation is done. It's pretty much like _alloca.*
Comment: btw, the memory is allocated on stack. compiler just needs to generate instructions to increase stack pointer for size * sizeof(int).
Comment: @chris: *How* it is done is different from *why* is it allowed in a compiler. Admittedly it looks like the intention might not actually have been getting to understand the implementation, but rather a *why* does it compile...
Comment: possible duplicate of [In C++ books, array bound must be constant expression, but why the following code works?](http://stackoverflow.com/questions/5947661/in-c-books-array-bound-must-be-constant-expression-but-why-the-following-cod)
Comment: @chris: That in fact provides the answer, but not the question you linked :)
Comment: @DavidRodríguez-dribeas, I guess I worded it a bit badly. That's what I meant in the second part of my first comment.
Answer: That is an extension on the compiler side. How does it work? Well, it works only to some extent.
The implementation basically moves the stack pointer a quantity that is dependent on the size of the array, and calls the memory in the middle by the name of the array. It only works to some extent because in VLAs the size is not an integral part of the type, which means that many constructs that can be used on regular arrays cannot be done with this type, like for example passing the array to a template by reference... sizeof is usually supplied but implemented as a runtime construct.
Answer: myArray in your example is allocated on the stack.  g++ has an extension that allows this trick.  The heap isn't necessary to do this, the compiler just generates code to increase the stack pointer by an amount that is computed at run time.
Answer: VLAs are an extension, many implementations have there own extensions to the C++ language. If you want g++ to complain that you are not adhering to the standard, pass -pedantic flag. VLAs are on the stack which is really fast, however, this is also the cause of problems since you have limited stack space. In C++ however, we have constructs like std::vector, etc., so there is really no need for there use.


Fixed number of columns in UICollectionView

Question: I am creating a chess board and want to use UICollectionView to do the grid layout. The problem is, I don't know how to set the number of columns to always be 8, so as to create a 8x8 grid.
I understand that UICollectionViewDelegateFlowLayout can be implemented to control the size of the items, but my question is will it work across all iOS devices (iPhone 4s - iPhone 6+, iPads). From what I have seen, it looks like i need to handle the size of the cells individually by each device type.
UICollectionView Set number of columns
Is anyone aware of a better solution to the problem?
Comment: Possible duplicate of [UICollectionView Set number of columns](http://stackoverflow.com/questions/14674986/uicollectionview-set-number-of-columns)
Answer: I'd forget the UICollectionView and go the a SpriteKit game. That will leave you way more control. You can even add a Game Scene in an "ordinary" iOS app.


Why does android go to onDestroy() after enabling large text in accessibility?

Question: But after going to onDestroy(), it would still go through onCreate(), onStart() and onResume(), by then though, some texts are missing and images are gone.
Answer: The Android system doesn't magically enlarge all applicable TextViews and custom views with text when you modify large text setting in accessibility. Instead it recreate the application with a new Configuration. If you are experiencing data loss afterwards, it means you should study Android Activity lifecycle some more.
There are all kinds of situations where an Activity would be destroyed & recreated by the Android OS, so you should really understand it to create a well-behaving app.


Criar link baseado em uma entrada do usuário

Question: Estou tentando criar uma página - que pode ser em qualquer linguagem, mas precisa ser armazenada em um arquivo único - para que um usuário digite seu login e a partir daí, seja criado um link para prosseguir a um site.
Esse site recebe o usuário em seu link, assim: https://site.com.br/usuario=LOGIN&empresa
O que consegui fazer foi link de redirecionamento estático:

    Go to site

Quero fazer uma caixa de texto com um botão ao lado para que ao clicar, o usuário seja redirecionado.
Answer: Algo bem simples e em javascript:

<form name=login>

<input type="text" name="username" size="9">
<input type="button" value="Entrar" onClick="Login()">

</form>

Comment: Cara, era isso! Muito obrigado! Funcionou perfeitamente.


How do I repeat a Sub row by row in VBA?

Question: I have been able to send emails from Excel through Gmail, with certain Excel cells defining the meta-data, body, and attachment of the email.
This sub obviously only runs on the selected cells.  What I'd like ideally is for this sub to run on the first row (row 2 in this case), and then run on the next rows, until it has reached the end.
The end goal is to be able to automate the sending of customized emails via Excel.
Here's what I have so far.
Sub CDO_Mail_Small_Text_2()
    Dim iMsg As Object
    Dim iConf As Object
    Dim strbody As String
    Dim Flds As Variant

    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")

    iConf.Load -1    ' CDO Source Defaults
    Set Flds = iConf.Fields
    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "MYEMAIL"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "MYPASSWORD"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Update
    End With

    If Sheets("Data").Range("G2").Value = "Statement" Then
    strbody = "Test" & Sheets("Data").Range("E2").Value
    Else
    strbody = "Test 2"
    End If

    With iMsg
        Set .Configuration = iConf
        .To = Sheets("Data").Range("A2").Value
        .CC = ""
        .BCC = ""
        .ReplyTo = Sheets("Data").Range("D2").Value
        .From = Sheets("Data").Range("C2").Value & "<EMAIL>" 'This just changes the name, the email will come from 'sendusername' above
        .Subject = Sheets("Data").Range("B2").Value
        .TextBody = strbody
        .AddAttachment "" 'don't put in "", just write direct path to file. Possible to do non-local?
        .Send
    End With

End Sub

Any help would be greatly appreciated!! Thanks everyone.
Comment: Add parameters to `Sub CDO_Mail_Small_Text_2()` for recipient, then change `.To = Sheets("Data").Range("A2").Value` to that parameter, e.g. `.To = Recipient`. Do the same for the other changing parameters. Lastly, run `foreach` loop, e.g. `foreach i in Sheets("Data").Range("A2:A10")` and then `Call Sub CDO_Mail_Small_Text_2(Parameters)`.
Comment: @nhee - Take the time to write this up as an answer using two subs.
Comment: @Jeeped and Jules Hill, please see below.
Answer: You'll need two subs, the first one being the existing one so send an e-mail, the second one to call the first one for a set of e-mail addresses.
For the first one, CDO_Mail_Small_Text_2, make these changes to make it "parameterized" (as opposed to the hardcoded version that it is now):
' Add some parameters to the Sub declaration
Sub CDO_Mail_Small_Text_2(RecipientAddress As String, ReplyToAddress As String, _
    Subject As String, FromAddress As String, Statement As String, _
    ValueOfColumnE As String)

    Dim iMsg As Object
    Dim iConf As Object
    Dim strbody As String
    Dim Flds As Variant

    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")

    iConf.Load -1    ' CDO Source Defaults
    Set Flds = iConf.Fields
    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "MYEMAIL"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "MYPASSWORD"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Update
    End With

    If Statement = "Statement" Then
        strbody = "Test" & ValueOfColumnE 'Use sub parameter
    Else
        strbody = "Test 2"
    End If

    With iMsg
        Set .Configuration = iConf
        .To = RecipientAddress 'Use sub parameter
        .CC = ""
        .BCC = ""
        .ReplyTo = ReplyToAddress 'Use sub parameter
        .From = FromAddress 'Use sub parameter
        .Subject = Subject 'Use sub parameter
        .TextBody = strbody
        .AddAttachment ""
        .Send
    End With
End Sub

The second one, let's call it Send_Messages, should look like this:
Sub Send_Messages()
    Dim RecipientAddress As String, ReplyToAddress As String, _
    Subject As String, FromAddress As String, Statement As String, _
    ValueOfColumnE As String

    ' change to match length of recipient list
    For Each i in Sheets("Data").Range("A2:A100")
        RecipientAddress = i.Value
        ReplyToAddress = i.Offset(0,3).Value
        Subject = i.Offset(0,1).Value
        FromAddress = i.Offset(0,2).Value
        Statement = i.Offset(0,6).Value
        ValueOfColumnE = i.Offset(0,4).Value

        Call CDO_Mail_Small_Text_2(RecipientAddress, ReplyToAddress, Subject, _
        FromAddress, Statement, ValueOfColumnE)

        ' Shorter alternative (the above variable declarations wouldn't be needed, then
        ' Call CDO_Mail_Small_Text_2(i.Value, i.Offset(0,3).Value, i.Offset(0,1).Value, _
        'i.Offset(0,2).Value, i.Offset(0,6).Value, i.Offset(0,4).Value)
    Next i
End Sub

Explanation:
The first sub was changed from one with hardcoded recipient addresses etc. to a parameter-based sub. It can now be run by other subs passing these parameters.
The second sub does just that. It goes through every cell in A2 to A100 and calls the first sub with the data from that row. While doing that, i becomes this cell from column A, hence in the first run, i equals Sheets("Data").Range("A2"). Column A contains the recipients, column B the subject lines and so on. To pass the subject line (and remaining parameters) to the CDO_Mail_Small_Text_2 sub, we use the .Offset(rows, cols) method. It is used to reference cells by their relative distance from another cell, i.e. i equals A2, so i.Offset(0,1) equals B2 whereas i.Offset(1,0) would equal A3. To make it easier to understsand, I am declaring variables for the parameters and setting them with the Offset method. As you can see in the code, this step can be skipped and the Offset method be used in the Call command directly.
Answer: Use a For loop to achieve this:
nRows = Cells(Rows.Count, 1).End(xlUp).Row
For i=2 To nRows
   //your code here, but referring to i instead of row 2...
Next

Where you refer to rows like this for example:
 .To = Sheets("Data").Range("A" & i).Value

Comment: It's highlighting "xlUp" and saying "Compile error: Invalid outside procedure".  It's not highliting "End" as a funciton
Comment: Also, I forgot to include, i have a "Option Explicit" at the very top of the code I originally posted.
Comment: Does the code you wrote go inside the "Sub" statements?
Comment: Yes, the code I wrote goed inside the Sub statements as well. And your code goes inside the For...Next loop, replacing al the "2"'s bij "& i" outside the quote marks. With option explicit you should also declare DIm i As Integer and Dim nRows as Integer at the top of your script.


Content management

Question: Is there any way to search and manage content via something more usable than admin/content page? There is no search patterns there, for example. I suppose that if the site will have several hundreds nodes it'll be a quite challenging task to find there what you want. It's even impossible to disable pager there!
So, any solutions?
Answer: For management purposes, check Total control and Views Bulk Operations.
For better search check Apache Solr.
Comment: Views Bulk Operations (or VBO) will add a (disabled by default) view to find and update nodes. Super handy and is one of the first modules I install.
Answer: You can check CMF module, it has a lot of options to filter from.
Show nodes, comments or both
Filter by author (select from drop-down list)
Filter by author (enter username in AJAX search field)
Filter by user role (shows nodes authored by any user in the selected role)
Filter by user status (active or blocked)
Filter by title or body substring
Filter by node created date (before/after)
Filter by node language
Displays a column in the content list with node creation time
Sort content list by any column: Title, Type, Author, Status, Time
Answer: in d7 admin/content is a views page, you can try to expand it: edit that view or better clone it, add filter node title with options Expose and contain, add author field if you want to select nodes by author, may by add all fields type Taxonomy reference - to select per terms - all Expose, if clone add own path like admin/my-admin-nodes, save, open the page - ta-da, more filters to select content nodes
Comment: my mistake (I thinking about commerce product. I dont know why :)), but the idea's to make administration list page with views like "admin/content" - but with more exposed filters
Comment: Yes, to be honest, I was disoriented a bit by your answer:) Nonetheless thanks for your response.

Content management


Moving pieces within a hexagonal grid?

Question: If I'm creating a HTML5 game that moves circles around a hexagonal grid what would be the best way to implement that with html and javascript?
Placing and spacing a div within each hex?
Using the canvas element?
Something else? SVG?
Thanks!
Answer: In terms of performance differences between various techniques you can try to look at jsgamebench, these few articles and video.
Comment: How did an answer made only of links become the accepted one?
Answer: Check this out : Creating a turn based hex grid in CreateJS
http://rishav-sharan.blogspot.fr/
<code>var stage;
var mapHeightHexNo = 5;            // Number of vertical hexes
var mapWidthHexNo = 10;             // Number of horizontal hexes
var mapStartX = 60;
var mapStartY = 60;
var mapHexSize = 50;

// calculate hex width and height. We will use these values to offset neighbouring hexes
var mapHexWidth = Math.sqrt(3)/2 * 2 * mapHexSize;
var mapHexHeight = 3/4 * 2 * mapHexSize;

function init() {
    //Create stage object - our root level container
    stage = new createjs.Stage("demoCanvas");

    // Call the function to craete the hex grid
    createMap(mapWidthHexNo, mapHeightHexNo);

    stage.update();
}

function createMap (mapSizeX, mapSizeY) {
    for (var i=0;i<mapHexHeight;i++) {                      // iterate over total number of hex rows
        for (var j=0;j<mapWidthHexNo;j++) {                 // iterate over each hex to be created in a single row.

            var hexY = mapStartY + i * mapHexHeight;

            //remember, each alternate row of hexes is offset in the x axis by half the width of the hex
            // so just add an extra half of the width of the hex, to the x axis displacement of rows 1, 3, 5 etc...
            if (i%2 == 0) {
                var hexX = mapStartX + j * mapHexWidth;
            }
            else {
                var hexX = mapStartX + j * mapHexWidth + 1/2* mapHexWidth;
            }

            //call the function to create individual hexes
            createHex (hexX, hexY, mapHexSize);
        }
    }
}

function createHex (x,y,size) {

    var hex = new createjs.Shape();
    hex.graphics.beginStroke("#aaa").beginLinearGradientFill(["#eee","#fafafa"], [0, 1], 0, y-20, 0, y+30).drawPolyStar(x,y,size,6,0,30);

    stage.addChild(hex);
}
</code>
Comment: You should include some details as link only answers are not recommended.  Check out this help doc: http://stackoverflow.com/help/how-to-answer

Moving pieces within a hexagonal grid?


Deepl API: Translate single word with context from whole sentence

Question: I want to translate single words out of a whole sentence using the DeepL API.
For example, the sentence might be: "How may I help you?"
If I now want to translate the word "help", DeepL might treat it as a noun (the help) or as verb (to help), both resulting in different outcomes in, for example, German language.
Is there a possibility to send the whole sentence as context to help DeepL disambiguate the word?
I tried to mark the word that I want to isolate. For example:
"How may I "help" you?"
But this seems to destroy the result or be ignored by DeepL.
Comment: Not sure if that exists. You could perhaps translate the full phrase first, resulting in `Wie kann ich Ihnen helfen?`, and then `help` on its own, which gets me `Hilfe`, and alternatives `helfen`, `Unterstützung` (using the web UI, but surely the API will provide similar data?) - and then look for which version you find in the translation of the full phrase ...? (But with the complexity of German declination and cases, that will probably not work all too well for more complex cases, I suppose.)
Comment: Thank you very much for your suggestion. As far as I understand, the API only returns one translation at the moment :/
Answer: Found out the answer. The docs describe here how to use context.
Attention: As stated by the docs, this feature is still in alpha as of now:
"The context parameter is an alpha feature as defined in section 3.1.5 of our terms and conditions. This means it could be changed or deprecated by DeepL at any point and without advance notice."


Uso do delete em um ponteiro de uma classe abstrata

Question: Lendo o livro A tour of C++, numa seção sobre vazamento de memória, quando me deparei com 3 afirmações em relação ao código abaixo:

A implementação de Smiley pode falhar ao deletar o ponteiro para mouth.
A tentativa de deletar o ponteiro retornado de read_shape() pode falhar.
Uma variável do tipo Shape* pode falhar ao tentar deletar o objeto para que aponta.

Texto original:

Experienced programmers will have noticed that I left open three opportunities for mistakes:
• The implementer of Smiley may fail to delete the pointer to mouth.
• A user of read_shape() might fail to delete the pointer returned.
• The owner of a container of Shape pointers might fail to delete the objects pointed to.

O CÓDIGO ABAIXO NÃO COMPILA, É APENAS UMA REPRESENTAÇÃO DO LIVRO PARA ENTENDER O PROBLEMA.
class Shape
{
    public:
        virtual ~Shape() {}
};

class Circle : public Shape
{
    public:
        Circle(Point _center, int _rad) : center { _center }, rad { _rad }
        {}

    private:
        Point center;
        int rad;
};

class Smiley : public Circle
{
    public:
        Smiley(Point center, int rad) : Circle { center, rad }, mouth { nullptr }
        {}

        ~Smiley()
        {
            delete mouth; // Referencia da primeira afirmação.
            for (auto eye : eyes)
                delete eye;
        }

        void set_mouth(Shape* _mouth)
        {
            mouth = _mouth;
        }

    private:
        std::vector<Shape*> eyes;
        Shape* mouth;

};

Shape* read_shape(std::istream& is)
{
    //Read kind_of_shape

    switch (kind_of_shape)
    {
        case Circle:
            //Read p, r.
            return new Circle { p, r };
            break;

        case Triangle:
            //Read p1, p2, p3.
            return new Triangle { p1, p2, p3 };
            break;

        case Smiley:
            //Read {Point, int} int p, r.
            Smiley∗ ps = new Smiley{p,r};
            return ps;
            break;
    }
}

Percebi que o problema da implementação estava então no Shape*, ou seja, um ponteiro para uma classe abstrata, mas não entendi qual o problema.
O texto ainda descreve:

Ponteiros para objetos alocados na free store¹ são perigosos: um ''plain old pointer''² não deveria ser usado para representar uma propriedade.

Texto original:

... pointers to objects allocated on the free store is dangerous: a ''plain old pointer'' should not be used to represent ownership.

A dúvida que ficou é: Porque o comando delete em uma varíavel do tipo Shape* talvez falhe?  .

[1][2] Não conheço uma tradução adequada.

A solução para este problema apresentada pelo texto é usando std::unique_ptr<Shape>() no lugar de Shape*.
Answer:
Percebi que o problema da implementação estava então no Shape*, ou seja, um ponteiro para uma classe abstrata, mas não entendi qual o problema

O problema não está em Shape nem no fato dela ser abstrata.
Problemas aparecem em read_shape() porque ela retorna um ponteiro, e em Smiley porque uma das propriedades é um ponteiro.
São pontas soltas e estão fora do controle. É esse o tema: "Avoiding Resource Leaks" em 4.5.3: evitar vazamentos.
Caso 1
Uma das propriedades de Smiley é um ponteiro para mouth, inicializado com nullptr no construtor padrão. Isso é um risco.

A dúvida que ficou é: Porque o comando delete em uma varíavel do tipo Shape* talvez falhe?

Não foi isso que o prof. Stroustrup escreveu. Ele escreveu:

"The implementer of Smiley may fail to delete the pointer to mouth"

algo como "o implementador de Smiley pode falhar em apagar o ponteiro para mouth". E se falhar aí já era. O autor não falava da possibilidade do comando delete falhar.
Caso 2
Shape* read_shape(std::istream& is)

Quem chamar isso recebe um Shape* e uma responsabilidade. É mais uma ponta solta --- loose-end --- e se o cara não liberar ja era também.
Caso 3
class Smiley : public Circle
{
    public:
        Smiley(Point center, int rad) : Circle { center, rad }, mouth { nullptr }
        {}

        ~Smiley()
        {
            delete mouth; // Referencia da primeira afirmação.
            for (auto eye : eyes)
                delete eye;
        }

        void set_mouth(Shape* _mouth)
        {
            mouth = _mouth;
        }

    private:
        std::vector<Shape*> eyes;
        Shape* mouth;

};

Veja o código do destrutor de Smyley acima: primeiro resolve o caso 1 e depois o caso 3.
Um Smiley tipo aranha vai ter 8 olhos. E se ele apagar só 7?
    private:
        std::vector<Shape*> eyes; // usually two eyes
        Shape* mouth;

Esse é o problema. Quem escreveu Shape ou Circle não tem culpa. Shape é abstrata e não tem problema, até alguém derivar desse modo.
De todo modo, responsabilidade não era pra ser um problema. É a vida.
Mas a idéia nesse ponto é introduzir unique_ptr<> como uma solução de não deixar essas coisas em aberto.
E reforçar o fato de que numa hierarquia de derivação de classes os construtores são chamados "de fora para dentro" e os destrutores ao contrário. Assim ao criar Smiley primeiro cria Shape depois Circle depois Smiley. Mas ao destruir Smiley a ordem é inversa.
Comment: Esse é o ponto: `Shape` não criou nenhum problema. `Smiley` introduziu uma vulnerabilidade. Não é o fim do mundo. E por isso os destrutores começam a ser invocados pela classe mais interna.  E o autor fala em hipóteses. "Se" o implementador falhar. Nesse exemplo não falhou. E eu escrevi errado: me referia ao destrutor de `Smiley` que faz o esperado e na ordem certa. Desculpe. Vou corrigir
Comment: Então no primeiro caso, eu fiz a confusão pois não soube traduzir o texto da maneira correta né?
Comment: E porque "o implementador de Smiley pode falhar em apagar o ponteiro para mouth" se o destrutor de Smiley invoca delete mouth? O destructor de Smiley não deveria ser chamado assim que saísse do escopo?
Comment: "Veja o código do destrutor de Shape: primeiro resolve o caso 1 e depois o caso 3." O destrutor de Shape está vazio, como ele resolve algo?


Change background image smoothly

Question: I tried to make changing background effect append to the body when page scrolls within specific amount which scroll at 50%,20%,10% rate of page
Here is what i got so far Full Screen Fiddle
Below is the sample code :
HTML :

...

And the script :
jQuery(window).scroll(function () {
   var JarakScroll = 200; // jarak scrol
   var JumlahJarakPasScroll = jQuery(window).scrollTop();
   if (JumlahJarakPasScroll > JarakScroll) {
       jQuery('html').addClass('scrolled');
   } else {
       jQuery('html').removeClass('scrolled');
   }
});

The background was changing but with no effect, anyone can help applying nice effect ?
Comment: What type of effect do you want? A fade?
Comment: Any, as long as its smooth. Not specifically.
Answer: If you want the background image to change with a nice effect it might be better if you have the background images applied to two divs that have 100% width and 100%height of the body and are placed correctly with z-index.
More specifically, place the first div on top of the second div and when you want the background image to change, fadeOut the first div. That'll be a neat effect. I'm assuming you can code this on your ownn.

Change background image smoothly


how to get an items from class of items

Question: I have a cell in (Table View List) of animals and i want to get from class of informations about the animals, what I want to do is get the name of the animal and put it in the cell.
This is ViewController class
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var TableViewList: UITableView!

    var NotKiller = Array<Animal>()
    var Killer = Array<Animal>()
    var Sections = ["NotKiller", "Killer"]

    override func viewDidLoad() {
        super.viewDidLoad()
        loadAnimals()
    }

    @IBAction func buAllAnimals(_ sender: Any) {
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return NotKiller.count

        } else {
            return Killer.count
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return Sections.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return Sections[section]
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        if indexPath.section==0 {
            cell.textLabel?.text = "" //here where I want to add the name

        } else {
            cell.textLabel?.text = "" // here where I want to add the name
        }

        return cell
    }
    func loadAnimals(){
    //here where I add the Items in to arrays
    }
}

This is the Animal class
import Foundation

class Animal {
    var Killing:String?
    var Name:String?
    var Des:String?
    var Image:String?

    init(Killing:String, Name:String, Des:String, Image:String) {
        self.Killing = Killing
        self.Name = Name
        self.Des = Des
        self.Image = Image
    }
}

Answer: This would do it
if indexPath.section==0 {
    cell.textLabel?.text = NotKiller[indexPath.row].Name
} else {
    cell.textLabel?.text = Killer[indexPath.row].Name
}

As a side note, your variable names should start with a lowercase letter to easily tell them apart from type name. Killer looks like it's a type but it's really a variable.
Answer: Try this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    if indexPath.section==0 {
        cell.textLabel?.text = NotKiller[indexPath.row].name

    } else {
        cell.textLabel?.text = Killer[indexPath.row].name
    }

    return cell
}

Comment: thak you so much <3

how to get an items from class of items


Sqoop-export the partitioned Hive table

Question: I have a Hive table partitioned by year and week columns. So the contents are stored in multiple recursive directories in Hive warehouse and in my case I have more than 100+ directories(partitions) for this table.
Here I am not sure how to mention the hive table's directory detail to the --export-dir property of the sqoop-export command.
Do I have to individually mention all 100* directory in separate sqoop-export commands?. Is there any way to mention about all the nested directories in a single sqoop-export command?.
Kindly also let me know if there is any other better way to solve this?.
[Note: I dont have Hcatalog in my environment, I just want to prefer the 'export to hdfs directory' as my last option ]
Answer: Try creating an External table with all the partitions and use the directory of external table in sqoop export.
1)  PART_TABLE (partitioned table);
2) Create exter table XX_DUMMY
()
Location
3) Insert overwrite XX_DUMMY  as select * from PART_TABLE
4) Run the Sqoop export
Or
Try export-dir /user/name/*
Answer: Have you tried with the following?

--hive-partition-key  Name of a hive field to partition are sharded on
--hive-partition-value     String-value that serves as partition key for this imported into hive in this job.

Sqoop-export the partitioned Hive table


Metric space consisting two elements.

Question: Suppose that $S$ be a set consisting exactly $2$ elements. Suppose we define a function $\displaystyle d:S \times S \to [0,\infty)$ by $\displaystyle d(x,y)=\begin{cases}1 &\text{ , if }x\not=y\\0 &\text{ , if} x=y\end{cases}$
How I can show that $d$ defines a metric on $S$ ?
Problem is on triangular inequality..To prove triangular inequality we need at least three points. How I can show the triangular inequality ?
Same problem for a set consisting only $1$-element or empty set.
What's the idea behind these ?
Comment: You can pick 3 elements among two,  obviously at least two of them will be equal, but that shouldn't bother you. Notice when you prove the triangular inequality for bigger metric spaces, you do not require that the 3 points are different.
Answer: The triangle inequality says:
$$
\text{For all } x, y, z, \;\; d(x,y) + d(y,z) \ge d(x,z).
$$
It may seem like it to you (thinking of it as a triangle), but $x,y,z$ do not have to be distinct. Two of them can be the same point.
However, triangle inequality with two or one point(s) is trivial. For instance, suppose $x = y$. Then the triangle inequality says
$$
d(x,x) + d(x,z) \ge d(x,z)
$$
which is true merely relying on the fact that $d(x,x) \ge 0$.
The same thing happens if $y = z$. Finally if $x = z$, we get
$$
d(x,y) + d(y,x) \ge d(x,x),
$$
which follows from the other property of a metric space, that $d(x,x) = 0$, and the facts $d(x,y) \ge 0$ and $d(y,x) \ge 0$.
The bottom line: The triangle inequality only says something "interesting" (not implied by the other properties of a metric space) when the three points of the triangle are distinct.
Comment: A lawyer might write the Triangle Inequality as " For any point, hereinafter called x, and any point hereinafter called y, and notwithstanding that x and y are different names, the point called x and the point called y may or may not be the same point, and  any point hereinafter called z..... (etc)" ...or something like that.
Answer: You don't need three points. Here's the statment of the triangular inequality:
$$\forall x,y,z\in S,d(x,z)\le d(x,y)+d(y,z)$$
Remark: This metric is called the discrete metric, and it can be defined on any nonempty set.

Metric space consisting two elements.


Effects of selection bias in training data introduced by previous model outputs

Question: I am developing a random forest for a binary classification problem where the trained data is heavily skewed towards one class (90% is class A and 10% is class B). The model scores data points based on their likelihood to be of class A, i.e., the number of trees in the forest that classify the data point as class A. This scoring effectively ranks data from the point that is most likely to be class A (top of the list), to the least likely (bottom of the list).
The training data is generated by another system on a monthly basis, and human operators review the data labeling each point as A or B. Suppose this model is used in a business process in such a way that the top 20% of the scored list (most likely to be A) is automatically labeled as A, and the remaining 80% is manually labeled as usual. This is going to introduce some errors in the automatically generated labels, and possibly more and more if we consider for automatic labeling increasing portions of the list (30% and above). However, if the model is good enough, we can live with such errors that define acceptable thresholds of precision, recall, accuracy, or whatever performance metric.
Since the manual labeling process typically changes over time, the model needs to be retrained every now and then. However, the training data will progressively contain less and less "obvious" examples of class A, because they will be excluded from the manual labeling process – effectively introducing a selection bias in the training data. This is of course unless we want to also learn from the previous model outputs (the 20% of data points labeled automatically), which intuitively doesn't sound very smart.
How do you expect the model to perform with such a selection bias in training data? What could happen if, rather than excluding from manual labeling 20% of data, we exclude 70% or 80%? The question might sound a little too generic, but this seems to me an interesting theoretical problem closely related to the application of Machine Learning approaches to real-world problems. I have never stumbled upon any paper about this. Maybe it also probably has a specific name, better than the generic "selection bias in training data", but I don't recall seeing this in the past.
Answer: This approach could in principle lead to problems, but those might be mitigated somewhat by use of random forest. In any event, it sounds like you might be able to get the data you need to evaluate the tradeoffs for your particular application.
Note that some recommend under-sampling of the majority class to minimize classification bias toward the majority class; see this answer for some discussion. So under-sampling the A class is not a problem in itself. The approach you describe does have 2 potential problems: throwing out true B-class members that happen to score in the top 20% (or top 30% or ...) along with the correctly classified A-class members, and a bias against certain predictor variable values or combinations that characterize those cases with the highest A-class probability.
Whether B-class members are being lost in that top 20% depends on the nature of the Receiver Operating Characteristic curve. As you have a rank-listing of probabilities along with true (manual) classifications, you can construct that curve directly yourself and evaluate its implications for losing B-class members in that top 20%. You don't discuss the relative costs of different misclassifications, but if you mostly care about identifying most B-class members (as I infer) and any substantial fraction of B-class members are included in that top 20% then I would be worried.
If the top 20% almost never include B-class members, then the issue is more subtle: whether you are selecting against particular characteristics of A-class members in a way that hurts the overall delineation of A from B. In some types of modeling approaches that might be a big problem, but the random choice of a small number of predictors at each node in constructing a random forest might make that less of an issue in your application. Again, you may have access to data needed to evaluate this directly. For example: start with a completely annotated data set, make a bootstrapped collection of samples from those data, develop models from each of those bootstrap samples with different choices for the highest (A-class) score cutoff for inclusion, and see how well they perform (with a proper scoring rule) in aggregate at different cutoffs in modeling the original data set.
Informally, the approach you describe might be thought of as applying a type of boosting to random forests.* That is, the boosting process can be thought of as sequentially fitting to the residuals from the earlier versions of a model, so if you think about the bottom 80% as being "residuals" then that is sort of what this approach is doing. In this analogy to boosted trees, however, note that you don't just throw away the earlier versions in true boosting; rather, you gradually add in the additional trees developed from fitting the residuals. So in your case you might want to consider gradually adapting your prior model rather than completely replacing it when new manually annotated data are available. Again, you probably have the data you need to see how well that would work.
I am, however, troubled by your statement that "the manual labeling process typically changes over time." I'm not quite sure what that means for you in practice, but if the ground truth of the labeling is changing it's not clear exactly what you are classifying. That could be the biggest problem of all.

*Although random forests and boosted trees are different, a quick web search did find a proposal to boost random forests. This isn't my specialty; there may be other similar proposals.
Comment: @st1led I don't have any experience with [Heckman correction](https://en.wikipedia.org/wiki/Heckman_correction) but it seems worth pursing if you can formulate a model for the origin of the selection bias. For the "refinement over time" of the labeling process, if you really think that is leading to better class assignments then more recent labeled data would be better, but you should reassess earlier-labeled cases with the newer version of the process, see how well class assignments agree, and evaluate what difference that might make to your modeling.
Comment: Thank you very much for the explanation, really thorough. I am indeed in the process of running an experiment as you describe, i.e., measuring the performance over models that progressively include the residual 80% of the previous training population.

As for the labeling process, unfortunately it does change over time. It's not major overhauls, but more of a refinement over time as operators become more experienced: the process is indeed complex, and in several cases operators themselves disagree on the labeling decisions. For this, I suppose the solution is training from more recent data.
Comment: After some additional reading, I read a few papers that seem to use Heckman correction in cases where selection bias is introduced in training data. This is not mentioned in the original answer, but could it be a further direction to explore?


Use PHP to delete section of .html file

Question: I have an HTML page I'd like to edit. I want to remove a certain section of the .html file such as.

......
......

How can I do this?
Comment: You mean once, or serially on request (and/or some condition)?
Answer: I would recommend using PHP's DOM library:
$dom = new DOMDocument;
$dom->loadHTML(''); // Or $dom->loadHTMLFile('file_name.html');

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[id="gg"]');
if($nodes->length)
  $nodes[0]->parentNode->removeChild($nodes[0]);

$dom->saveHTML(); // Or $dom->saveHTMLFile('file_name.html');

Answer: $file = file_get_contents("index.html");
$file = preg_replace('/
.*?<\/div>/im', '' $file);
file_put_contents($file);

I not tested this code.
Attention: nested divs break html structure.
Comment: See: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
Comment: What happens if there's a nested `div` in there?
Comment: I know, but in simple tasks regex is good. nested div break html. thanks for advise.
Answer: You might have some luck using an XML (or HTML) parser. This one for PHP 5 looks really easy to use, and provides a mechanism for finding a particular element by ID and then setting its contents to an empty string.

Use PHP to delete section of .html file


Finding the Limit $\lim_{x\to 0} \frac{\sin x(1 - \cos x)}{x^2}$

Question: Here's the problem.
$$\lim_{x\to 0} \frac{\sin x(1 - \cos x)}{x^2}$$
I really don't know where to start with this. Please help.
Comment: Do you know L'Hopital's rule, where you can differentiate the numerator, and the denominator, so long as you have an indeterminate form? Here, you have an indeterminate form as is: $\frac 00$.
Comment: Well we haven't learned about derivatives in class yet, but after watching a video, L'Hopital's Rule seems very useful. Thank you
Comment: Use [Maple](http://www.maplesoft.com/support/help/Maple/view.aspx?path=examples/Calculus1SingleStepping) to this end.
Answer: I assume you know that $$\lim_{x \to 0} \frac{\sin x}{x}=1.$$
Now, $$\lim_{x \to 0} \frac{1-\cos x}{x^2} = \lim_{x \to 0} \frac{(1-\cos x)(1+\cos x)}{x^2 (1+\cos x)}=\lim_{x \to 0} \frac{\sin^2 x}{x^2(1+\cos x)},$$
and therefore $$\lim_{x \to 0} \frac{1-\cos x}{x^2}=\lim_{x \to 0} \left( \frac{\sin x}{x} \right)^2 \times\lim_{x \to 0}\frac{1}{1+\cos x}=\frac{1}{2}.$$
Finally, $$\lim_{x \to 0} \frac{\sin x (1-\cos x)}{x^2}=\lim_{x \to 0} \sin x \times \lim_{x \to 0} \frac{1-\cos x}{x^2}=0 \times \frac{1}{2}=0.$$
Answer: Hint:
$$\lim_{x\to 0}\frac{\sin x(1-\cos x)}{x^2} = \left(\lim_{x\to 0}\frac{\sin x - \sin 0}{x-0}\right)(-1)\left(\lim_{y\to 0}\frac{\cos y - \cos 0}{y-0}\right),$$
assuming the two limits on the right hand side exist (why do they exist?).
Comment: Hmmm...sorry I'm kinda lost on how you came up with the right side.
Comment: @Steve: $\frac{\sin x(1-\cos x)}{x^2} = \frac{\sin x}{x}\cdot\frac{1-\cos x}{x} = \frac{\sin x-\sin 0}{x-0}\cdot(-1)\cdot\frac{\cos x-\cos 0}{x-0}$
Answer: Applying the l'Hopital rule, if you put: $f=\frac{\sin(x)(1-\cos(x))}{x^2}=\frac{g(x)}{h(x)}$ you get:
$$L=\lim_{x\to 0}f=\lim_{x\to 0}\frac{g'(x)}{h'(x)}$$ wich gives:
$$L=lim_{x\to 0}\frac{\cos(x)-\cos(x)^2+\sin(x)^2}{2x}$$
If you apply l'Hopital again you get:
$$L=\lim_{x\to 0}\frac{\sin(x)(4\cos(x)-1)}{2}=0$$
Comment: Yeah, that makes a lot of sense, however I think my professor wants us to do it without using derivatives.
Answer: Hint: Use the fundamental trigonometric limit:
$$
\lim_{x\to 0}\frac{\sin x}{x}=1
$$
For more informations about $\lim_{x\to 0}\frac{\sin x}{x}$ see  Manipula Math Applets for $\lim_{x\to 0}\frac{\sin x}{x}$. For $\lim_{x\to 0}\frac{1-\cos x}{x}$,
\begin{align}
\lim_{x\to 0}\frac{1-\cos x}{x}=&
 \lim_{x\to 0}\frac{1-\cos x}{x}\frac{1+\cos x}{1+\cos x}\\
=& \lim_{x\to 0}\frac{1-\cos ^2x}{x\cdot(1+\cos x)}\\
=& \lim_{x\to 0}\frac{\sin^2x}{x\cdot(1+\cos x)}\\
=& \lim_{x\to 0}\frac{\sin x}{x}\frac{\sin x}{(1+\cos x)}\\
=& \lim_{x\to 0}\frac{\sin x}{x}\cdot\lim_{x \to 0}\frac{1}{(1+\cos x)}\cdot \lim_{x\to 0}(\sin x)\\
=& 1\cdot\frac{1}{2}\cdot0
\end{align}


php script not running in fedora

Question: I was a windows user earlier and wants to shift to Linux. For that I have installed LAMP in my FC 15. But I am unable to run any php script there. I saved my files to var/www/html , but when I tried to run http://localhost/test.php it shows a blank page.
NB:rpm -q php shows php-5.4.9-1.fc15.remi.x86_64.
Please help
Comment: Is your server status is in  start ? let us know what happens in http:localhost in your browser? do u have the open php in fedora ? check with php -v for version ? @Suraj Hazarika
Comment: When you go to test.php and right click page and view source do you see your PHP code?
Comment: `php -v` shows `PHP 5.4.9 (cli) (built: Nov 22 2012 10:37:24)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies`. `localhost/` shows a normal Fedora test page with powered by Apache
Comment: obviously the issue in php page...check with sample codes or update your code with posts.. will get you back with the issues..@Suraj Hazarika
Comment: you can use the binaries provided by your distribution - it is much simpler, dont wanna think about the external distributions
Comment: What does `test.php` contain?
Comment: Are there any meaningful contents in ``/var/log/httpd/error_log*``? On fedora, error output goes there by default.
Answer: You don't have the correct permissions set.
Comment: That would result in a 500 or 403 error, no? OP is getting a blank page so page is being served, but the PHP is not being processed by the looks of it.
Comment: `ls -l` shows `-rw-r--r--. 1 root root 23 Dec 14 18:19 test2.php
-rw-r--r--. 1 root root  0 Dec 14 18:17 test.php
`
Answer: Do the following...
yum install php*

Install all the packages, then don't forget to restart apache/LAMP.
If still not coming, try http://localhost/index.html and tell the output if possible the  content of httpd.conf . The docroot may be wrong.
Answer: I think you need to install php-common packages also
yum install php-common

will do.
Answer: open your terminal and paste those two commands :
systemctl start httpd.service

and

php script not running in fedora