Como pegar o src de uma img do  Angular 7

Question: Estou fazendo um Rss Feed e quero pegar uma imagem do <content:encoded> e usar como thumbnail, como resolver?
Estou usando esse feed como exemplo: http://parceriasocialdeempregos.com.br/feed
parseXml(data: any){
  let parser = new DOMParser();
  let doc = parser.parseFromString(data, 'application/xml');

  let objs = [];

  this.xml2 = doc.getElementsByTagName('feed')[0] || doc.getElementsByTagName('rss')[0] || [];

  /*  RSS */
  if (this.xml2.tagName === 'rss') {

    let items = doc.querySelectorAll("channel > item");
    for (let el of items as any) {
      let obj = {
        "title": el.querySelector("title").textContent,
        "link": el.querySelector("link").textContent,
        "author": el.querySelector("creator").textContent,
        "description": el.querySelector("description").textContent,
        "pubDate": el.querySelector("pubDate").textContent,
        "content": el.querySelector("encoded").textContent,
        "thumbnail": el.getElementsByTagName('img').item(1).getAttribute('src')
        /* Erro ao tentar pegar a img */
      }
      objs.unshift(obj);
    }
    this.items = objs;
  }
}

Answer: A imagem esta em um CDATA, logo ele é como texto para o DOMParser e não como HTML, então não vai encontrar nada, por isso .getElementsByTagName('img') retorna um NodeList vazio
Outra coisa, tags com namespace como <content:encoded> precisam usar uma função para tal, se getElementsByTagName pega elementos normais então para elementos com namespace deve-se usar getElementsByTagNameNS.
Olhando no seu FEED o namespace de :content é http://purl.org/rss/1.0/modules/content/, então um exemplo para pegar o conteudo seria:
var ces = doc.getElementsByTagNameNS('http://purl.org/rss/1.0/modules/content/', 'encoded');

console.log(ces.length);

Veja um teste, vai retornar 1 se encontrar ao menos uma tag:

var data = `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    >

<channel>
    <title>Parceria Social de Empregos</title>
    <atom:link href="http://parceriasocialdeempregos.com.br/feed/" rel="self" type="application/rss+xml" />
    <link>http://parceriasocialdeempregos.com.br</link>
    <description>Um blog com vagas de emprego</description>
    <lastBuildDate>Sat, 06 Jul 2019 17:05:44 +0000</lastBuildDate>
    <language>pt-BR</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <generator>https://wordpress.org/?v=4.9.10</generator>

    <image>
        <url>http://parceriasocialdeempregos.com.br/wp-content/uploads/2019/01/cropped-logo_01-1-32x32.png</url>
        <title>Parceria Social de Empregos</title>
        <link>http://parceriasocialdeempregos.com.br</link>
        <width>32</width>
        <height>32</height>
    </image>
    <item>
        <title>Estágio loja de autopeças Av Ipanema</title>
        <link>http://parceriasocialdeempregos.com.br/06/07/2019/estagio-loja-de-autopecas-av-ipanema-3/</link>
        <comments>http://parceriasocialdeempregos.com.br/06/07/2019/estagio-loja-de-autopecas-av-ipanema-3/#respond</comments>
        <pubDate>Sat, 06 Jul 2019 17:05:44 +0000</pubDate>
        <dc:creator><![CDATA[Watanabe]]></dc:creator>
        <category><![CDATA[Vaga de Emprego]]></category>

        <guid isPermaLink="false">http://parceriasocialdeempregos.com.br/?p=25590</guid>
        <description><![CDATA[Você gosta do mundo automotivo? Esta pode ser sua chance de conhecer mais sobre a área! Obrigatório: – Estar cursando o 2º ou 3º ano do Ensino Médio em 2019; – Residir próximo a Avenida Ipanema; – Gostar do mundo automotivo; – Aptidão em português e matemática; – Disponibilidade aos domingos. Enviar currículo para email@example.com]]></description>
        <content:encoded><![CDATA[

]]></content:encoded>
        <wfw:commentRss>http://parceriasocialdeempregos.com.br/06/07/2019/estagio-loja-de-autopecas-av-ipanema-3/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>
    </item>
</channel>
</rss>`;

var parser = new DOMParser();
var doc = parser.parseFromString(data, 'application/xml');

var ces = doc.getElementsByTagNameNS('http://purl.org/rss/1.0/modules/content/', 'encoded');

console.log(ces.length);

Claro que como eu disse no começo o conteúdo dentro de CDATA não é processado, pois justamente este é o objetivo do CDATA (Para que serve <! [CDATA []]> em XML?), então no caso terá que fazer outro parse, já fizemos o parse para o RSS agora é o parse para o conteudo HTML dentro deste RSS, exemplo:

var data = `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    >

<channel>
    <title>Parceria Social de Empregos</title>
    <atom:link href="http://parceriasocialdeempregos.com.br/feed/" rel="self" type="application/rss+xml" />
    <link>http://parceriasocialdeempregos.com.br</link>
    <description>Um blog com vagas de emprego</description>
    <lastBuildDate>Sat, 06 Jul 2019 17:05:44 +0000</lastBuildDate>
    <language>pt-BR</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <generator>https://wordpress.org/?v=4.9.10</generator>

    <image>
        <url>http://parceriasocialdeempregos.com.br/wp-content/uploads/2019/01/cropped-logo_01-1-32x32.png</url>
        <title>Parceria Social de Empregos</title>
        <link>http://parceriasocialdeempregos.com.br</link>
        <width>32</width>
        <height>32</height>
    </image>
    <item>
        <title>Estágio loja de autopeças Av Ipanema</title>
        <link>http://parceriasocialdeempregos.com.br/06/07/2019/estagio-loja-de-autopecas-av-ipanema-3/</link>
        <comments>http://parceriasocialdeempregos.com.br/06/07/2019/estagio-loja-de-autopecas-av-ipanema-3/#respond</comments>
        <pubDate>Sat, 06 Jul 2019 17:05:44 +0000</pubDate>
        <dc:creator><![CDATA[Watanabe]]></dc:creator>
        <category><![CDATA[Vaga de Emprego]]></category>

        <guid isPermaLink="false">http://parceriasocialdeempregos.com.br/?p=25590</guid>
        <description><![CDATA[Você gosta do mundo automotivo? Esta pode ser sua chance de conhecer mais sobre a área! Obrigatório: – Estar cursando o 2º ou 3º ano do Ensino Médio em 2019; – Residir próximo a Avenida Ipanema; – Gostar do mundo automotivo; – Aptidão em português e matemática; – Disponibilidade aos domingos. Enviar currículo para firstname.lastname@example.com]]></description>
        <content:encoded><![CDATA[

]]></content:encoded>
        <wfw:commentRss>http://parceriasocialdeempregos.com.br/06/07/2019/estagio-loja-de-autopecas-av-ipanema-3/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>
    </item>
</channel>
</rss>`;

var parser = new DOMParser;
var doc = parser.parseFromString(data, 'application/xml');

var ces = doc.getElementsByTagNameNS('http://purl.org/rss/1.0/modules/content/', 'encoded');

//Executa só se a tag existir
if (ces.length) {
    let ce = ces.item(0).textContent;
    let htmlParser = new DOMParser;
    let htmlDoc = parser.parseFromString(ce, 'text/html');

    let imgs = htmlDoc.getElementsByTagName('img');

    console.log(imgs.item(0));
}

Resolução
Para adiantar, toda introdução da resposta foi para explicar como funciona as coisas para que no futuro você adapte para outros códigos, mas neste código especifico você pode fazer assim (leia os comentários):
  //Pode aplicar o ANY direto na variavel
  let items: any = doc.querySelectorAll("channel > item");

  for (let el of items) {
    let obj = {
      "title": el.querySelector("title").textContent,
      "link": el.querySelector("link").textContent,
      "author": el.querySelector("creator").textContent,
      "description": el.querySelector("description").textContent,
      "pubDate": el.querySelector("pubDate").textContent,
      "content": el.querySelector("encoded").textContent,
      "thumbnail": this.getImgFromEncodedTag(el)
    }
    objs.unshift(obj);
  }

  ...

private getImgFromEncodedTag(el)
{
    let ces: any = doc.getElementsByTagNameNS('http://purl.org/rss/1.0/modules/content/', 'encoded');

    //Executa só se a tag existir
    if (ces.length) {
        let ce = ces.item(0).textContent;
        let htmlParser = new DOMParser;
        let htmlDoc = parser.parseFromString(ce, 'text/html');

        let imgs = htmlDoc.getElementsByTagName('img');

        //Verifica se existem imagens
        if (imgs.length) {
             return imgs[0].src;
        }
    }

    //Se não houver imagens retorna null
    return null;
}


Angles And Their Measurements

Question: I have an intuitive understanding of what degrees and radians are and what arc length, subtending, area of the sector and the derivation of the formula $$s = r \cdot \theta.$$ However due to lack of reasoning skills, I am unable to get started with these problems.
The problems go like this.

Find the angle between the minute hand of a clock and the hour hand when the time is (a) 5:25, and (b) 6:10.
Find the distance between the two points on the earth,when the arc joining these points subtends an angle $5$ minutes at the earth's centre, the radius of the earth being $6370$ kms.
The moon's distance from the earth is $360000$ kms and the diameter subtends an angle of $31$ minutes at the eye of the observer. Find the diameter of the moon.
Comment: For the first two questions: you need to see the correspondence between the 60 minutes in an hour and 360 degrees in a whole circle...
Comment: For the final pair of questions you need to see the correspondence between the $360\times 60$ minutes of arc and $2\pi$ radians in a whole circle
Comment: These are very good and sensible problems. You better acquire a thorough understanding of the issues occurring therein, so that problems of this kind become "no problem at all" before going on to  more serious matters in mathematics. This has nothing to do with "reasoning skills" but with a good intuition for scales and linear relations between variables.
Answer: Hints:

the hour hand moves $2\pi$ radians in $12$ hours, while the minute hand moves $2\pi$ radians in $1$ hour.
$60$ minutes of arc is $1$ degree and $360$ degrees is $2\pi$ radians.
same as for 2.

Apply $s=r\theta$, remembering this is true when $\theta$ is in radians and $s$ is arc length.
Answer: a) hour hand at $25\frac{25}{60}$ mark, minute hand at 25 mark, 60 marks to the circle so difference is $\frac{25}{60}\frac{1}{60}$

Find the circumference of the earth and multiply by the fraction of a circle which 5 minutes corresponds to.
Comment: Would be glad if you spoon feed me with step by step solutions for both the problems!!

Angles And Their Measurements


European cloud hosting provider

Question: I'm trying to find a good european cloud hosting provider. For legal reasons we can not host our service in the US or with an american company operating in the European union (rackspace).
All we want is a couple of linux machines that we can manage our selves.
Any good suggestions?
Best regards,
Niclas
Comment: More suitable for serverfault than SO, voted to move it.
Answer: Your question is wrong on stackoverflow.
Anyway, I don't know what do you mean with "good"
you have no criterias... so if you want a cheap&good one check
http://www.alvotech.de/

server in germany or netherland (your choice)

or if you want a very secure and one of the best for business I know of you can try
http://www.artmotion.eu/
it's not cheap but I think it's well worth it

server in switzerland

European cloud hosting provider


Turn two CGPoints into a CGRect

Question: How can I, given two different CGPoints, turn them into an CGRect?
Example:
CGPoint p1 = CGPointMake(0,10);
CGPoint p2 = CGPointMake(10,0);

How can I turn this into a CGRect?
Answer: This will take two arbitrary points and give you the CGRect that has them as opposite corners.
CGRect r = CGRectMake(MIN(p1.x, p2.x),
                      MIN(p1.y, p2.y),
                      fabs(p1.x - p2.x),
                      fabs(p1.y - p2.y));

The smaller x value paired with the smaller y value will always be the origin of the rect (first two arguments). The absolute value of the difference between x values will be the width, and between y values the height.
Comment: @nacross: Good note, but do be aware that when compiling for 64 bit, `CGFloat`s are double size, not float size, so you'd lose information if you used `fabsf`.
Comment: Nice solution, I would change fabs to fabsf for more strict type matching.
Comment: `r` will not contain either of the points offered in the question. A`CGRect`'s `maxX` and `maxY` are *not* included in the rectangle, and points along those boundaries will fail `CGRectContainsPoint`
Comment: @ChristopherSwasey: I've tweaked the answer to avoid misleading on this point (thanks) although note that this is not necessarily true: if one of the given points is the origin, it is "contained". This is a useful comment but only matters if you care about that (it seems unlikely that the OP did).
Comment: @BenZotto Indeed, if one of the points is the origin it will be contained, but any other corner will not—but neither of the points in the question were the origin. Where it will have a real effect is using this method as part of drawing code—that will result in a rectangle a point too small in at least one dimension.
Answer: A slight modification of Ken's answer.  Let CGGeometry "standardize" the rect for you.

CGRect rect = CGRectStandardize(CGRectMake(p1.x, p1.y,  p2.x - p1.x, p2.y - p1.y));

Answer: Swift extension:
extension CGRect {
    init(p1: CGPoint, p2: CGPoint) {
        self.init(x: min(p1.x, p2.x),
                  y: min(p1.y, p2.y),
                  width: abs(p1.x - p2.x),
                  height: abs(p1.y - p2.y))
    }
}

Answer: Assuming p1 is the origin and the other point is the opposite corner of a rectangle, you could do this:
CGRect rect = CGRectMake(p1.x, p1.y,  fabs(p2.x-p1.x), fabs(p2.y-p1.y));

Comment: If you already know that p1 is the origin (it's not in the OP's example), you don't need the `fabs`. But then you're kind of making the caller do the hard work in advance.
Answer: This function takes any number of CGPoints and gives you the smallest CGRect back.
CGRect CGRectSmallestWithCGPoints(CGPoint pointsArray[], int numberOfPoints)
{
    CGFloat greatestXValue = pointsArray[0].x;
    CGFloat greatestYValue = pointsArray[0].y;
    CGFloat smallestXValue = pointsArray[0].x;
    CGFloat smallestYValue = pointsArray[0].y;

    for(int i = 1; i < numberOfPoints; i++)
    {
        CGPoint point = pointsArray[i];
        greatestXValue = MAX(greatestXValue, point.x);
        greatestYValue = MAX(greatestYValue, point.y);
        smallestXValue = MIN(smallestXValue, point.x);
        smallestYValue = MIN(smallestYValue, point.y);
    }

    CGRect rect;
    rect.origin = CGPointMake(smallestXValue, smallestYValue);
    rect.size.width = greatestXValue - smallestXValue;
    rect.size.height = greatestYValue - smallestYValue;

    return rect;
}

Answer: This will return a rect of width or height 0 if the two points are on a line
float x,y,h,w;
if (p1.x > p2.x) {
    x = p2.x;
    w = p1.x-p2.x;
} else {
    x = p1.x;
    w = p2.x-p1.x;
}
if (p1.y > p2.y) {
    y = p2.y;
    h = p1.y-p2.y;
} else {
    y = p1.y;
    h = p2.y-p1.y;
}

CGRect newRect = CGRectMake(x,y,w,h);

Answer: let r0 = CGRect(origin: p0, size: .zero)
let r1 = CGRect(origin: p1, size: .zero)
let rect = r0.union(r1).standardized

Comment: Please add more information that may be useful for a future reader.
Comment: `union` makes rectangle from two rects.

So, make two zero size rect from point.

`standardized ` is optional. This method convert rect to normal.

Turn two CGPoints into a CGRect


Como utilizar corretamente BufferedInputStream?

Question: Estou criando uma aplicação na qual eu preciso ler de um arquivo de vídeo e transmitir pacotes de dados que poderão ser lidos novamente em memória. Estou usando o formato de vídeo Ogg, por ser open source e porque achei mais simples de entender. Eu utilizei o BufferedInputStream para ler do arquivo, porém como os primeiros 28 bytes são informações do cabeçalho eu optei por utilizar o método buffer.read(byte[]) da seguinte forma:
byte[] buffer = new byte[28];
FileInputStream in = new FileInputStream("/path/video.ogv");
BufferedInputStream buffStream = new BufferedInputStream(in);
buffStream(buffer);

Assim, eu posso ler uma sequência de bytes de maneira mais rápida. Ao inspecionar o elemento buffer no debug do eclipse, eu notei que valores acima de 128 estão negativos, isso, creio eu se deve ao fato de que o número máximo que consigo representar com 1 byte seja 128. Sei que os valores estão corrompidos pois ao abrir o arquivo no https://hexed.it, eu consigo visualizar o valor correto em hexadecimal. Por exemplo, o valor que corresponde a B5 = 181(dec) está como -75. Como posso utilizar este método e contornar essa corrupção dos dados?
Obs.: Utilizar um decodificador de vídeo que já efetua isto de maneira transparente não é uma opção. Faz-se necessário ser desta forma porque estou desenvolvendo uma aplicação distribuída e os pacotes de dados serão destinados a outros computadores.
Answer: Isso daí não é corrupção de dados. É uma pegadinha irritante da linguagem Java.
A maioria das linguagens de programação representa um byte como um número de 0 a 255, ou seja um valor sem sinal (unsigned). Por algum motivo, o Java quis ser diferente e decidiu que o byte tem sinal (signed), e portanto, ele tem valores de -128 até 127.
Na forma binária, os valores relativos dos bits no esquema unsigned são 128 (mais significativo), 64, 32, 16, 8, 4, 2 e 1 (menos significativo). No Java, o primeiro valor é -128 ao invés de 128.
Desta forma, para converter um valor na faixa -128 a 127 para a faixa 0 a 255, você faz isso:
public static int tirarSinalDoByte(byte a) {
    return (a + 256) % 256;
}

Ou então essa outra implementação (mais eficiente, mas um pouco menos didática):
public static int tirarSinalDoByte(byte a) {
    return a & 0xFF;
}

Para converter de volta:
public static byte formarByte(int a) {
    if (tirarSinalDoByte(a) != a) throw new IllegalArgumentException();
    return (byte) a;
}

Nesta conversão da volta, se você tiver certeza que o valor do a está sempre na faixa correta ou quiser desprezar qualquer coisa que não seja os últimos 8 bits caso não esteja, você pode retirar este if ou então apenas fazer o cast para byte diretamente sem ter que chamar uma função específica para fazer isso.
Comment: Muito obrigado pelo esclarecimento.
Comment: @RodrigoBrito Se esta resposta resolveu o seu problema e não restou nenhuma dúvida, peço que marque-a como aceita/correta ao clicar no ✅ abaixo do número da votação.
Comment: @CarlosHeuberger Sim. Obrigado pela sugestão. De fato, era exatamente isso que eu havia colocado no método `formarByte`.


IAM for Google Cloud DNS: Restrict permissions to one managedZone?

Question: I'm trying to restrict DNS Administrator role permissions to only one ManagedZone, say the resource <code>//dns.googleapis.com/projects/my-project/managedZones/example-com</code>
When I go to the troubleshooter, It says that's not a valid resource name. What gives?
Answer: Google Cloud DNS does not support assigning IAM policies to managed zones.
At this time you can only assign an IAM policy at the project/folder/org resource level which grants rights to all managed zones within the resource (project/folder/org).


nodejs version on EPEL repository

Question: Current stable node.js version is v0.12.2. I just run yum update on my machine and it updated node to v0.10.36.
Why is my EPEL repo version so old compared to current stable one? Can I update node to latest version through yum or do I have to compile it myself?
I have CentOS 6.6
Comment: 0.10.36 dates to January 26. Is that so terribly old as to be unusable? Remember that EL and EPEL are meant to be _stable_.
Comment: @MichaelHampton, at the time I'm checking the nodejs.org website, the current stable release is at version 5.1.0. https://nodejs.org/dist/v5.1.0/ ; I think we can all agree that the version on EPEL is significantly outdated, like, 4 major stable revisions outdated. :/
Comment: @JesúsZazueta It's a little difficult for anyone to keep up when a framework has 4 major stable revisions in less than a year! That alone would make me not want to work with node.js (but I have other reasons too).
Comment: @MichaelHampton ah, you're right. It's a bit frightening how fast is the JavaScript app ecosystem moving. Even the node & io.js versions themselves look a bit weird. Oh well. Thanks!
Answer: RHEL 6 was released in 2010 and one of the consequences of choosing an enterprise distribution with long term support cycles is you'll end up with seeming old versions of software, a trade-off for stability and better support for third-party software.
(Note: an old version do not equate to insecure, read up on backporting of security updates.)
Typically if you need something more recent you should look for a the next major release i.e. RHEL 7.
You might get more recent supported versions of certain software in older Red Hat Enterprise Linux releases by subscribing to the  Software Collections channel.
Node.js  is part of the SC channel currently supported as release 0.10 so that seems about correct.
Comment: RHEL / CentOS 7 are also on node.js 0.10.X
Answer: Regarding why EPEL does not contain the latest versions, taken from the EPEL Guidelines and Policies:

Why not a rolling release with latest packages like what was in Fedora
  Extras?
Why should we? That would be what Fedora Extras did and worked
  and works well for it -- but that's mainly because Fedora (Core) has
  lots of updates and a nearly rolling-release scheme/quick release
  cycle, too. But the Enterprise Linux we build against is much more
  careful with updates and has longer life-cycle; thus we should do the
  same for EPEL, as most users will properly prefer it that way, as they
  chose a stable distro for some reasons -- if they want the latest
  packages they might have chosen Fedora.
Sure, there are lots of areas where having a mix of a stable base and
  a set of quite new packages on top of it is wanted. Maybe the EPEL
  project will provide a solution (in parallel to the carefully updated
  repository!) for those cases in the long term, but not for the start.
  There are already third party repositories out there that provide
  something in this direction, so users might be served by them already.
Further: A rolling release scheme like Fedora Extras did is not
  possible for many EPEL packages for another reason, new packages often
  require new versions of certain core libraries. This will cause
  problems in EPEL because we won't be able to provide updated libs as
  it would replace libraries in the core OS.
Example: This document was written round about when RHEL5 got
  released; many packages that get build for RHEL5 can't be build for
  RHEL4 at this point of time already, as the RHEL4-gtk2-Package is two
  years old and is too old for many current applications, as they depend
  on a newer gtk2. So if even if we would try to have a rolling scheme
  with quite new package we'd fail, as we can't build a bunch of package
  due to this dependencies on libs; in the end we would have a repo with
  some quite new packages while others are still quite old. That mix
  wouldn't make either of the "latest versions" or "careful updates
  only" sides happy; so we try to target the "careful updates only"
  sides. Remember, EPEL's support and updates cycle is much longer then
  Fedora's.

nodejs version on EPEL repository


What does changing config.assets.version number do?

Question: What does changing config.assets.version number do?
I understand that the assets expire (as it is written in the comments) but what does it do in the background?
would it delete all the compiled assets? or does it take that version number and uses it somewhere else?
Comment: FYI that as of right now this is broken for Sprockets >= v3.0. (The default for new Rails applications). See also [this other stackoverflow question](http://stackoverflow.com/questions/32548755/rails-4-2-rails-application-config-assets-version-doesnt-invalidate-digest-asse) and [this sprockets-rails github issue](https://github.com/rails/sprockets-rails/issues/240).
Answer: It will precompile assets with another fingerprints (the code appendend to the file name), making all the client's browsers download the files again.
In other words, as you said, it expires the caches in the client's browsers.
Comment: Humm, I don't know about Heroku, but deploying with Capistrano the precompiled assets are deleted and regenerated on every deploy.
Comment: would it delete the older assets from the server (on heroku)?


Evaluate $\int_{1}^{e}\frac{u}{u^3+2u^2-1}du.$

Question: I'm trying to solve
$$\int_{1}^{e}\frac{u}{u^3+2u^2-1}du.$$
My first approach was to factorise and then do a partial integration. However the factorisation $(u+1)\left(u+\frac{1}{2}-\frac{\sqrt{5}}{2} \right)\left(u+\frac{1}{2}+\frac{\sqrt{5}}{2} \right)$ leads me to heavy calculations. How would you proceed to solve this?
This is a continued calculation of Solving $\int_0^1 \frac{dx}{e^x-e^{-2x}+2}$ with substitution
Comment: Partial fractions is the right track. Unfortunately, sometimes is quite tedious. You are in the right track !!!.
Answer: As $$u^3+2u^2-1=(u+1)(u^2+u-1)$$
Write,
$$\frac u{u^3+2u^2-1}=\frac A{u+1}+B\frac{\dfrac{d(u^2+u-1)}{du}}{u^2+u-1}+\frac C{u^2+u-1}$$
$$u=A(u^2+u-1)+(2Bu+B)(u+1)+C(u+1)$$
Set $\displaystyle u+1=0$ to find $A$
Now comparing the coefficients of $u^2$, $0=A+2B\iff B=?$
Again comparing the constants $0=-A+B+C\implies C=?$
Observe that the second integral $\displaystyle\int B\frac{\dfrac{d(u^2+u-1)}{du}}{u^2+u-1}du=B\int\frac{d(u^2+u-1)}{u^2+u-1}=?$
For the third,  $\displaystyle\int\frac C{u^2+u-1}=4C\int\frac{du}{(2u+1)^2-(\sqrt5)^2}$
use $\#1$ of  this
Or set $\displaystyle 2u+1=\sqrt5\sec\theta$
Comment: Sorry, I don't understand how that would help me. To me, that just looks more confusing.
Comment: @iveqy He's showing that you can split the fraction into ones that are easier to work with.
Comment: @oliveeuler yes I understand that. And that was my approach to, however I've learnt that you need to fully factorise before you can do that. He's using some clever trick involving the derivator of $u^2+u-1$ so avoid factorising. How does that work?
Comment: @labbhattacherjee Could you explain how you can do a partial integration without fully factorise the denominator?
Answer: Hint: Obserse that $u^3 + 2u^2 -1$ has $u+1$ as a factor.
Comment: I did, see the factorisation above. But how to proceed then?
Answer: Hint: $$u^3+2u^2-1=(u+1)(u^2+u-1).$$  Completing the square $$ u^2+u-1= u^2+u\frac{1}{4}-\frac{1}{4}-1=(u+1/2)^2-5/4.$$
Now use partial fraction
\begin{align}
\frac{1}{(u+1)((u+1/2)^2-5/4)}=\frac{A}{u+1}+\frac{Bu+C}{( u+1/2)^2-5/4}
\end{align}
We find that $ A=-1, B=1, C=0$, so that
\begin{align}
I&=\int { \frac{-1}{u+1} du}+\int{ \frac{u}{(u+1/2)^2-5/4}du}
\\
&=-\ln ( u+1 )+J
\end{align}
now to find $ J$, since $$denominator= \frac{5}{4}\left({  (\frac {2}{\sqrt 5}  (u+1/2))^2-1 }\right)$$ we assume $(\frac{2}{\sqrt5}(u+1/2))= w$ to get
\begin{align}
J=constant \int\frac{\sqrt5 w-1}{w^2-1}dw
\end{align}
Finally, setting $ w=\sec\theta $ and proceed $\cdots $
Comment: I don't understand the middle expression of your second equation...
Comment: You can proceed now


Parsing a double from a string which holds a value greater than Double.MaxValue

Question: Consider the following java code:
String toParse = "1.7976931348623157E308"; //max value of a double in java
double parsed = Double.parseDouble(toParse);
System.out.println(parsed);

For the mentioned value of 1.7976931348623157E308 everything makes sense and one gets the correct output.
Now, if one tries to parse 1.7976931348623158E308 (last digit before E incremented) you still get the maximum value printed into the console!
Only after trying to parse 1.7976931348623159E308 (again the last digit got incremented) and greater one gets Infinity.
Same behaviour for the corresponding negative values.
Why is ... 8E308 parsed to ... 7E308 and not Infinity?
Comment: Has this any relevance for any application?
Comment: I guess that you're having fun with edge cases. Have you looked at the source code?
Comment: @AlexWien just stumbled upon this by "accident", now I'm curious
Comment: @BastiM: compare the binary representation of your decimal values to the binary values specified in the API.
Comment: @basti you will loose your curiouseness when you look at that code, i have looked at it. ;-)
Answer: The SE 7 version of the parseDouble documentation refers to the valueOf documentation which says:

Note that the round-to-nearest rule also implies overflow and underflow behaviour; if the exact value of s is large enough in magnitude (greater than or equal to (MAX_VALUE + ulp(MAX_VALUE)/2), rounding to double will result in an infinity and if the exact value of s is small enough in magnitude (less than or equal to MIN_VALUE/2), rounding to float will result in a zero.

This is consistent with the statement that the rounding to type double is by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic.
You have to imagine the conversion being done by first calculating the nearest floating point number ignoring the exponent limitation, and then checking whether the exponent fits. Double.MAX_VALUE is the closest number under that rule to some numbers that are strictly greater than it.
To confirm this is normal rounding behavior, consider the following program:
    public class Test {
      public static void main(String[] args) {
        double ulp = Math.ulp(Double.MAX_VALUE);
        System.out.println(ulp);
        System.out.println(Double.MAX_VALUE);
        System.out.println(Double.MAX_VALUE+ulp/2.0000000001);
        System.out.println(Double.MAX_VALUE+ulp/2);
      }
    }

It outputs:
1.9958403095347198E292
1.7976931348623157E308
1.7976931348623157E308
Infinity

Adding something even slightly less than half a ulp to Double.MAX_VALUE does not change it. Adding half a ulp overflows to infinity.
Comment: +1 for the example code, this was the part which wrapped my head around it! thanks, patricia


Deployment strategy for servers on internal network

Question: I am following composer based workflow for Drupal 8, in which I commit only custom code and use composer install to install it on another environment.
However, on new workflow, the dev, test, staging instances are on Internal network, with no access to Internet (due to security reasons).
Can you suggest a deployment strategy to use in this scenario, so that I don't have to commit the whole files in git repository, as is.
PS: I am ok with something like Acquia pipelines, where things are 'compiled' into a branch, which is used for deployment. But using that is ruled out, as the code can't be sent to outside because of security concerns.
Answer: The correct way is to use Acquia BLT. It generates a deployment artifact, which can be deployed anywhere.
So that the composer will stay in local and the deployment artifact can be committed to a different branch for deployment, with all the dependencies.
Comment: Well, it's one way. You can also write a shell script that mimics what BLT does and run that manually. I've dome it both ways.
Comment: To add to this, you could set up Jenkins internally too, or use the CI capabilities of GitLab to automate deployments either by BLT or manual script(s).


How do I calculate the derivativee of the function $x\mapsto \sqrt{x}$ in two ways?

Question: I need to calculate the derivative of the following function in two ways:
$$
f\colon\mathbb{R}^+\to\mathbb{R}^+,
\quad x\mapsto \sqrt{x}
$$
a) by means of differential quotient
b) using the derivation rules for powers
I need to determine the equation of the tangent of the graph of $f$ at the point $(3,f(3))$. Sketch the graph of $f$ and the tangent. Can someone do this?
a) I know that and I get $1/(\sqrt{x}+\sqrt{x})$
b) $1/(2\sqrt{x})$
But what they mean with "determine the equation of the tangent"? How to do this last part? I would be really thankful if someone could help me.
Comment: The equation of the tangent is $y-f(3)=f'(3)\cdot(x-3)$, by definition of tangent.
Comment: The tangent is the straight line passing through the point of tangency $(3,f(3))$ and whose slope is the same as the function at that point: $f'(3)$
Answer: Regarding the tangent:
The tangent of the graph of $f$ at the point $P=(3, f(3))$ is the line with the same slope as the graph has in $P$ and going through the point $P$.
Therefore starting with the general line equation $f_l(x) = m x + t$, $m$ denotes the slope and $t$ the y-intercept.
To achieve the same slope as the graph of $f$ in $P$ just set $m = f'(P_x)$, so to the value of the derivation in the specified point (to $m = 1/(2 \sqrt{P_x})$ with $P_x = 3$ in your case, so $m = 1/\sqrt{6}$).
To get $t$ one can use the general line equation again $y = f_l(x) = mx + t$, which is true for every point, so also for $P$, which leads us to $P_y = m P_x + t$, or $t = P_y - m P_x$, with $P_x = 3$ and $P_y = f(3) = \sqrt{3}$ in your case, so $$t = \sqrt{3} - (1/\sqrt{6}) 3 = \sqrt{6}/\sqrt{2} - (\sqrt{3}\sqrt{3})/\sqrt{6} = \sqrt{6}/\sqrt{2} - \sqrt{3}/\sqrt{2} = $$
$$ = (\sqrt{6} - \sqrt{3})/\sqrt{2} = (\sqrt{2} - 1) \sqrt{3/2}$$
(however you like to express it)
This results in the tangent of the graph of $f$ in $P$: $f_t(x) = x/\sqrt{6} + (\sqrt{6} - \sqrt{3})/\sqrt{2}$
Regarding the plot:
Every line with an equation given in the form $f(x) = m x + t$ can be plot simply by starting at the point $(0|t)$ (Value t on the y axis) and giving the line a slope of $m$ ($n$ units in direction of the x axis leading to $n m$ units in the direction of the y axis).
Preferable here:
As you know the tangent goes through the point $P$, you can also just start off the point $P$ and apply a slope of $m$ again.
Hope that helped you :)
Comment: still don't know how to make graph...
Comment: The main job for plotting a line is basically the equation. If you know the equation, you can proceed by a fixed scheme. The slope intercept form is a very common form, so there are mass of good guides for this.

For example look at:

https://www.mathsisfun.com/equation_of_line.html
or
http://www.webmath.com/gline.html
Comment: https://www.khanacademy.org/math/cc-eighth-grade-math/cc-8th-linear-equations-functions/8th-slope/v/graphing-a-line-in-slope-intercept-form shows it in a video. It uses exaktly the slope intercept form, except that they print y instead of f(x) and b instead of t


Why Define the Box Topology in Terms of a Redundant Basis?

Question: Let $\{X_i\}$ be an arbitrary collection of topological spaces.
Let $X = \prod X_i$.
I have seen in Munkres' textbook on Topology, for example, that we can define the box topology $\tau$ on $X$ via the basis $\mathcal{B} = \{\prod U_i : U_i$ is open in $X_i\}$.
But why define $\tau$ in terms of what $\mathcal{B}$ generates if they are the same sets (am I mistaken that they are indeed the same sets)?  Then my question specifically is if, under this definition, $\tau = \mathcal{B}$, why discuss a basis at all?
Comment: You seem to be confused: the set $\mathcal B$ in your question is not a basis for the product topology as soon as there are infinitely many factors; in fact, its elements are no even open in general!
Comment: Sorry -- I meant "box topology" in the text (it's been corrected now).
Answer: Yes, you are mistaken; for example, consider the box topology on $\mathbb{R}\times\mathbb{R}$ (which is actually just the same as the normal topology). Let $U=(0,1)\subset\mathbb{R}$, which is an open set. Then
$$(U\times\mathbb{R})\cup (\mathbb{R}\times U)$$
is a "thick plus sign" in $\mathbb{R}^2$, which cannot be expressed as $V\times W$ for any open $V,W\subset \mathbb{R}$.
Comment: Amazing how something so simple escaped my attention for several weeks.  This has clarified a lot of other proofs I've read involving Cartesian products.  Thanks!
Comment: Glad I could help!
Comment: In case it helps anyone else with similar thoughts to my own -- the reason why this escaped my attention is that I've been intentionally not visualizing Cartesian products in the plane (instead viewing them as sets of ordered pairs across lines parallel to each other).  But in two-dimensions this makes it hard for certain sets to be visualized.  For example, the set you gave above falsely looks at first glance like $\mathbb{R} \times \mathbb{R}$ from this birds eye view since each point on the two lines (each representing $\mathbb{R}$) is covered.  If this doesn't make sense then ignore :)
Answer: In general $\tau\supsetneqq\mathscr{B}$. For a simple example, consider $X=\square^\omega\Bbb R$, the box product of countably infinitely many copies of $\Bbb R$. Let $z$ be the point whose coordinates are all $0$. Then $X\setminus\{z\}$ is an open set not in $\mathscr{B}$.
For that matter, let $X$ be any Hausdorff space with at least two points. Let $\Delta=\{\langle x,x\rangle:x\in X\}$, the diagonal in $X\times X$ (which has the same topology both as a Tikhonov and as a box product). Then $X\setminus\Delta$ is an open set not in $\mathscr{B}$. To see this, let $x,y\in X$ with $x\ne y$; clearly $\langle x,y\rangle,\langle y,x\rangle\notin\Delta$. However, if $\langle x,y\rangle,\langle y,x\rangle\in U\times V$, then $x,y\in U\cap V$, and therefore $\langle x,x\rangle,\langle y,y\rangle\in(U\times V)\cap\Delta$.
Comment: Why are you using $\langle\cdot,\cdot\rangle$ to denote ordered pairs?
Comment: @Peter: Because it's a standard (albeit less common) convention that I prefer; parentheses are already overloaded. I suspect that most of the people who use it have some set-theoretic background.
Comment: What is meant by the $\square$ symbol?
Comment: @user1770201: I defined it in the answer: it's the box product. When the factors are all the same, as they are here, so that it's actually a box power, the number of factors is sometimes superscripted on the box, as I did it, rather than on the space.


Example of cont. map. $\psi: \mathbb{R}_l \to \mathbb{R}_l$ such that $ \phi: \mathbb{R}\to \mathbb{R} $, def. by $ \phi(x)=\psi(x) $, is not cont.

Question: $ \mathbb{R}_l $ denotes the Sorgenfrey line or the Lower limit topology generated by the half-open intervals $ [a,b) $ and $ \mathbb{R} $ denotes the usual euclidean topology in $ \mathbb{R} $. Can someone help me to find a continuous mapping $\psi: \mathbb{R}_l \longrightarrow \mathbb{R}_l$ such that $ \phi: \mathbb{R}\longrightarrow \mathbb{R} $, defined by $ \phi(x)=\psi(x) $, is not continuous? I can't find the same question here on this site, and I have a hard time coming up with any mapping myself.
Answer: There are a lot of ways to achieve this. For instance, you can notice that $\mathbb R_l$ is disconnected, since $(-\infty,0)\cup[0,\infty)$ is a separation. In particular, there is a surjective continuous map $\mathbb R_l\to\{0,1\}$. Compose this with an injective map $\{0,1\}\to\mathbb R_l$ and you are done.
Comment: @GjermundJohansen: No, the surjective map does not have to be constant. Namely, map $(-\infty,0)$ to $0$ and $[0,\infty)$ to $1$. This is continuous (consider the preimages of open sets). The injective map can be anything you want.
Comment: @GjermundJohansen: No need to go via $\{0,1\}$. Yes, you can define $\psi$ in the way you are proposing, but note that specifying where $(-\infty,0)$ and $(0,\infty)$ are mapped is not enough to define a map. You could define for instance $$\psi(x)=\begin{cases}0;&x\in(-\infty,-1),\\x+1;&x\in[-1,0),\\2;&x\in[0,2),\\3-\frac{1}{x-1};&x\in[2,\infty).\end{cases}$$ This maps $(-\infty,0)$ to $[0,1)$ and $(0,\infty)$ to $[2,3)$. In addition to this, it solves your problem. However, there are simpler ways, take for instance $$\psi(x)=\begin{cases}x;&x<0\\x+1;&x\geq0.\end{cases}$$ This also works.
Comment: To show that these two maps $\psi$ are continuous, it is sufficient to show that $\psi^{-1}[a,b)$ is open for all $a<b$, since the intervals $[a,b)$ are a basis for the Sorgenfrey topology. You can also use the fact that $\{(-\infty,-1),[-1,0),[0,2),[2,\infty)\}$ and, in the second case, $\{(-\infty,0),[0,\infty)\}$ are finite closed covers.
Comment: @GjermundJohansen: You can use real analysis, unless someone forbids you from doing so. The notion of continuity is the same here. But yes, you can also find an open subset whose preimage is not open. (Note: this does **not** automatically mean that the preimage has to be closed **(!)**. Sets can be open, closed, both or neither.) For the two functions $\psi$ defined above, we have $\psi^{-1}(1,\infty)=[0,\infty)$ and $\psi^{-1}(0,\infty)=[0,\infty)$, respectively.
Comment: The surjective map you are suggesting must be constant in order to be continuous, right? But I am still not getting it. What can the injective map look like? The composite map $ \psi(x)=g\circ f(x) $ must be such that $ \psi ^{-1}([a,b))=[c,d) $ for some $ c\le d $, right? Or do I think all wrong?
Comment: Aha, I think I get it. But why go via $ \{0,1\} $? Can't I just define $ \psi $ to take $ (-\infty,0) $ to $ [0,1) $, say, and $ (0,\infty) $ to $ [2,3) $? I can see this is continuous in $ \mathbb{R}_l $ since the preimage of open sets are open, but how can I argue that it is not continuous in $ \mathbb{R} $? Neither $ [0,1) $ nor $ [2,3) $ are open in $ \mathbb{R} $, so there are no preimages of open sets to consider.
Comment: I can see that those $\psi$ that you defined are continuous in $\mathbb{R}_l$, but why are they not continuous in $\mathbb{R}$? Using real analysis it is obvious that it is not continuous, but I can't do that, can I? Don't I need to find an open set in $\mathbb{R}$ having closed preimage? And that does not seem to be the case here...
Answer: Let $\phi(x)=1$ if $x\geq 0$ and $\phi(x)=0$ if $x<0.$
For any $S\subset \mathbb R_l$ we have $$\phi^{-1}S\in \{\emptyset, \mathbb R_l, [0,\infty), (-\infty,0)\},$$ so $\phi^{-1}S$ is Sorgenfrey-open, and $\phi$ is Sorgenfey-continuous. But $\phi$ is obviously not $\mathbb R$-continuous.
Remark: It is not necessary to use a different symbol ($\psi$) for the function when considered as a function on $\mathbb R.$ It's the same function as $\phi.$
Remark: This is the same idea as in the answer by Dejan Govc, which seems to have generated a lengthy discussion.


Odds of a given Windows EventID to be unique for a Source?

Question: I am using the basic NRPE plugins for Nagios to passively monitor Windows Eventlog. The plugin allows for an EventID exception list as a command argument. So, for instance, I can block any event that has an EventID of 1024.
Of course, this doesn't look at the source of the event.
What I am wondering is on the chance of two Sources using the same EventID. Some spot checking(googling the eventid) has found only uniqueness, so it might be an acceptable risk, but I would like your thoughts. Have you ever come across two sources that use the same EventID?
Comment: My Google link shows at least four Sources that generate Event ID 1024, as just one example.
Comment: Here's your answer - https://www.google.com/#output=search&sclient=psy-ab&q=event+id+1024&oq=event+id+1024&gs_l=hp.3..0l4.1444.4456.0.4618.104.22.168.22.214.171.124.1027.10j2.12.0....0...1c.1.23.psy-ab..0.13.975.JiBlfw612z4&pbx=1&bav=on.2,or.r_cp.r_qf.&bvm=bv.49967636,d.dmg&fp=6acc75de4afeeb84&biw=1680&bih=910
Comment: Have you ever come across two sources that use the same EventID?
Answer: There's no restriction on event sources using any ID the programmer decides. To give a concrete example, my ts_block script (source "ts_block"), for example, uses event IDs 1, 2, 3, 256, and 257. A search of those event IDs in a public event database (like-- and I hold my nose as I say this-- eventid.net) will show you many, many other sources that use these same event IDs.
If you're comparing only on the event ID then you're not comparing on enough.


How do I find out where the Mercurial hook file is being called from?

Question: On the project I am working on there is a standard pre-commit hook for mercurial that looks something like this:
python:hookhgext.messagevalidation.checkCommitMessage

I would like to find out where the python script is located so I can create my own hook script that also calls this.
How would I either find the location of this file or also call this hook from a python script?
Answer: Accoring to docs

The value of the hook must start with the text "python:", and continue
  with the fully-qualified name of a callable object to use as the
  hook's value.
  …
  So long as you have the module name and PYTHONPATH right, it should
  "just work"

I.e. in your case Mercurial imports hookhgext.messagevalidation (from any possible for import location) and call checkCommitMessage from it.
I know nothing about Python, but for me hookhgext.messagevalidation is "messagevalidation" something inside "hookhgext.py", and "hookhgext" is the usual installed python-module in it's (installed modules) default location(s)


trying to get current datetime inserted into db but producing an error

Question: i have a column with the datatype DATETIME and im trying to get it to automatically insert the current date and time. i tried setting the value to NOW() but it gave the following error

ERROR 1292: 1292: Incorrect datetime value: 'NOW()' for column 'date' at row 1

does anyone know how this is accomplished? im using mysql workbench
Comment: Are you inserting `"NOW()"` with quotes? Maybe it's understood as a string where you really want NOW() as a function without the quotes.
Comment: im using mysqlworkbench like i said i dont have any original code im using a gui
Comment: It would probably be useful to see that actual statement you have written
Comment: set `DEFAULT CURRENT_TIMESTAMP` in the table definition and it's fixed
Comment: Martin im using mysql workbench so im not writing the query. @lelio, i have already created the tables and its columns. i tried to alter the table via workbench and tried to set the column in question to "DEFAULT CURRENT_TIMESTAMP" but it gave an error. also didnt give an error code it just says it contains errors and cannot be accepted
Comment: Please show up your original code so I can try to help up you.
Answer: NOW() should return the datetime correctly which should match the field type. As I mentioned in the comment, you might be inserting the value "NOW()" as a literal string, which isn't a valid datetime format. Make sure you don't have quotes around NOW().
Comment: i didnt have quotes around NOW(). is the datatype i specified correct to use the now function?
Comment: @Cole-p in your question when you said "automatically", do you mean setting a default value? If this is what you mean, you can take a look here at this question because there's a slight dependency on the version you're using: https://stackoverflow.com/questions/168736/how-do-you-set-a-default-value-for-a-mysql-datetime-column
Comment: thanks, thats what lelio was saying but its not working for me. i have already created the table in mysql workbench so when i try to alter it using the gui it doesnt accept it. what would be the sql code to alter the column so i can try input it manually?
Comment: have this sorted now found the option in mysqlworkbench
Comment: @Cole-p make sure to remove the two paranthases `()` after `DATETIME` in Workbench like this: https://pasteboard.co/IqonETd.png


Como implementar um sistema de confirmação de usuário convidado por email

Question: No sistema, o cadastro de usuário não será livre. Cada usuário será convidado por e-mail pelo administrador para participar.
Na tabela de usuários tenho, resumidamente, os seguintes atributos:
<code>$table->increments('id')->unsigned();
$table->string('nome', 45);
$table->string('email', 64)->unique();
$table->string('username', 45)->nullable();
$table->string('senha', 20)->nullable();
$table->string('codigo', 100)->nullable();
$table->boolean('ativo')->default(false);
</code>
Nunca trabalhei com esse tipo de confirmação, então imaginei o seguinte algoritmo (sequência):

Para convidar um usuário, o administrador deve preencher o nome e email do convidado.
Sendo assim, o usuário convidado receberá um email com o convite.
No e-mail encaminhado, haverá um link que aponta para a rota: hostname/codigo (onde codigo é um atributo com conteúdo único para cada usuário convidado).
Caso essa rota for acessada o usuário se torna ativo no sistema.

Esse passo-a-passo para autenticação de usuário seria, relativamente, o mais correto? E a senha? Seria conveniente o administrador setar uma senha inicial para o convidado? Preciso de ideias.
Comment: Acho que esses passos estão no caminho certo, fazer uma senha ou deixar o usuario setar a senha fica a seu critério, na verdade não existe um "problema" para ser solucionado nessa pergunta, ficou ampla, veja se consegue reformular, antes que vá para a fila de suspensão.
Answer: Você Pode fazer o seguinte, crie um sistema onde fica pedindo email e nome da pessoa, e por traz faz com que crie um token com número randômico e depois criptografa em md5, salve esse valor, o id do usuário, o email do usuário e o nome dessa pessoa. Na função mail(), crie um link com o código gerado, email e id tudo em um link.
Crie uma página para receber esses valor e valide no banco de dados, se  for correto, crie uma session de qualquer nome e coloque um valor e depois direcione para uma pagina, onde o usuário irá concluir o cadastro, com nome completo e bla bla. Essa página só vai entrar se existir a session que vai ser criada se o resultado for positivo. Lembre-se de fazer a pagina deletar o token dele, para outra pessoa não usar.
Se quiser pode criar um outro script para atualizar o token se o usuário entrar no link e não concluir o cadastro e enviar um novo email com o link.


difference between char *(arr[5]) and char (*arr)[5]

Question: It appears that I don't practically know the difference between
char *(arr[5]) and char (*arr)[5]
Logically, as it is with type-definitions, char *(arr[5]) is a pointer to an array of 5 char's, char *arr[5] is an array of char pointers then what (*arr)[5] will be then? Or it makes no difference ?

I did some tests and found out that these 3 declarations are different.
For instance if I use char (*arr)[5] it totally allows me to do that arr = malloc(2), otherwise it moans about illegal conversions.

Can someone explain the differences between these declarations, when they are used and it will be a huge plus if this also includes may I do arr = malloc(2) to dynamically allocate an array of [5] chars, as it allows me to semantically do so with char (*arr)[5] although giving me stack overflows when being used. (disclaimer: [] suggests stack allocation, so it doesn't make much sense as a heap memory address cannot point to stack memory address as far as I am not aware)
Comment: `char (*arr)[5]` is a pointer to an array of 5 `char`s... I think `char *(arr[5])` is just an array of 5 pointers to `char`, same as without the parentheses?
Comment: `char (*arr)[5]` and `char *(arr[5])` *are* different.  It's `char *(arr[5])` and `char *arr[5]` that I think are the same.
Comment: I concur with @Dmitri. Since [] already has higher precedence than *, `char *(arr[5])` and `char *arr[5]` must be the same.
Comment: @Dmitri true that makes sense, but EiC c-interpreter finds them for different. This is where I got confused.
Comment: @Dmitri Ahh yes, these two are the same, yeah. So I cannot dynamically allocate a pointer to [5] chars ? Make sense but why technically ? And the interpreter allows it for some reasons.
Comment: If you just want to dynamically allocate an array of 5 `char`s, you just need a regular `char` pointer: `char *arr = malloc(5);`.  You might want a pointer to arrays of chars if you were allocating an array of arrays of `char`, though: `char (*arr)[5] = malloc(10 * sizeof(*arr));` for an array of 10 arrays of 5 `char`s.
Comment: @Dmitri Yes, an array of arrays of char is what I meant. Oh so this is legal.. I just forgot about it and seems that I couldn't find it anymore in the internet. By the way isn't sizeof(*arr) just 5 in this case
Answer: char *(arr[5]) equals to char *arr[5] and it means you have array of pointers that each of them points to a character so arr[0] can points to a character and arr[1] can points to a character and so on.
For example you can write your code like this:
char *(arr[5]);// or char *arr[5]
char a = 'a',b='b',c='c';
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
printf("a=%c b=%c c=%c \n",*arr[0],*arr[1],*arr[2]);

But (*arr)[5] means you have an array of 5 characters and you want to point it.
For example you can write your code like this:
char (*arr)[5];
char str[5] = "Hell";
arr = &str;
printf("%s\n",*arr);


Explain WolframAlpha output

Question: I just inputted (x-10)^2+(y-2)^2 = 5^2, y= k*x+2 into the WolframAlpha input text field. Under the section dedicated to
Real solutions it states that $x=\frac{15}{2}$. I do not understand this output, although I do recognise and agree with it.
Can someone please help me understand the output (as in how it found it)?
Thanks in advance.
Edit:
The assignment is

A circle has the equation $(x-10)^2+(y-2)^2=5^2$. Line $t$ goes through the point $p(0,2)$ and is tangent to the circle.
Comment: You are working too hard for this problem. You might want to recall that a tangent and a radius can be perpendicular.
Comment: But how do I use that information? I know they can, but I am not aware of how to implement it ..
Comment: You've already represented the tangent as $y=kx+2$, no? Then the radius would be (why?) $y-2=-\frac1{k}(x-10)$. The intersection of these two lines is the tangency point on the circle, which should be in terms of $k$. Plug into your circle equation, and solve.
Comment: That's just one of the coordinates of the two intersection points you got, no?
Comment: True. But I still don't understand how I can make this assignment with proper arguments.
Comment: What should I _plug_ into the circle equation?
Comment: Do you agree that the coordinates of a tangency point ought to satisfy the equation of the associated circle?
Comment: Yes, I do fully agree.
Answer: HINT: solve the equation $$(x-10)^2+(kx+2-2)^2=25$$ for $x$
simplifying you get the following quadratic equation
$$x^2(1+k^2)-20x+75=0$$
can you solve this?
after dividing by $$1+k^2\ne 0$$ we get
$$x^2-\frac{20x}{1+k^2}+\frac{75}{1+k^2}=0$$ we get
$$x_{1,2}=\frac{10}{1+k^2}\pm\sqrt{\left(\frac{10}{1+k^2}\right)^2-\frac{75}{1+k^2}}$$
Comment: Thanks for your answer, but I do not see how to do that.
Comment: ok a few minutes i will help you
Comment: why the $-1$? i don't understand it
Comment: Nope, I can't. Are you able to? :)
Comment: I appreciate your effort, but I do not see how this explains it. :/
Answer: You are asking wolfram for which values of $x,y$ and $k$ the equations $(x-10)^2+(y-2)^2 = 5^2$ and $y= kx+2$ are true. These are 2 equations in 3 different variables so there are infinitely many solutions. Under real solutions, wolfram shows you the values of $x,y$ $k$ such that the equations are true and such that $x,y$ and $k$ are real numbers (no complex part, see complex numbers).
Comment: Your question wasn't asking for that...
Comment: I am aware of the distinction, but how did **it** find it?
Comment: I wasn't aware of that but I have rectified it.
Answer: I just managed to find out why:
Tangents to the circle $(x-10)^2+(y-2)^2=5^2$ have the equation $$(x-10)(x_P-10)+(y-2)(y_P-2)=5^2$$
I can insert values for $y_P$ and $x_P$: $$(x-10)(0-10)+(y-2)(2-2)=5^2$$ where the right side equals $0$. Then I isolate for x:
$$-10x+100=25$$
$$-10x+75=0$$
$$75=10x$$
$$\frac{15}{2}=x$$
Comment: If you're allowed to use calculus, implicit differentiation can quickly derive the expression for the tangent line from the circle's equation.
Comment: Yea, unfortunately, I have not yet learned about differentiation, calculus or other higher level stuff. I guess that would also be smart to tag? ;)
I actually just about started Cartesian geometry (in the plane). However, I greatly appreciate your sharing of knowledge. :)
Comment: That's why supplying context is important when asking a question on this site. When I gave you the hint above in the comments, I didn't know that you knew the compact formula for a circle tangent, so I gave you the usual "blind" method to proceed. In any case, you should still try finishing that route, even if only for practice in algebraic manipulation.
Comment: Of course. I will have that in mind next time I ask a question.

Explain WolframAlpha output


Interpret Negative-Binomial mixed-model output in R

Question: I am modelling the number of jobs in a year, with a random intercept to account for regional variation.
How do I interpret the model output when using the model to predict/ for inference?
For example, using the log-link function I would do the following to work out the expected number of jobs in year 2 in London:
exp(Intercept + Year*2 + London_intercept) = exp(0.23290 + -0.13369*2 + 0.42820729) = 1.482496

But this value is way too low, I expect way more jobs than 1.5 in a year. Do I instead interpret it as 70% increase over the mean? If so what is the mean? Could someone clarify what to do please?
summary output:
> summary(m8)
Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
 Family: Negative Binomial(0.9321)  ( log )
Formula: Jobs ~ 1 + Year + (1 | Region)
   Data: df_jobs

     AIC      BIC   logLik deviance df.resid
  3554.5   3575.9  -1773.3   3546.5     1564

Scaled residuals:
    Min      1Q  Median      3Q     Max
-0.7836 -0.6187 -0.5081  0.3613  7.2595

Random effects:
 Groups Name        Variance Std.Dev.
 Region (Intercept) 0.1597   0.3996
Number of obs: 1568, groups:  Region, 14

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.23290    0.13610   1.711    0.087 .
Year        -0.13369    0.01572  -8.502   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
     (Intr)
Year -0.536

Random intercepts for region:
$Region
                      (Intercept)
East Midlands         -0.02413869
East of England        0.18654921
Kent, Surrey & Sussex  0.14610941
London                 0.42820729
North East            -0.42892509
North West             0.48852281
Northern Ireland      -0.26330415
Scotland               0.41420383
South West             0.15415043
Thames Valley         -0.80072297
Wales                 -0.05975189
Wessex                -0.53037342
West Midlands          0.15126500
Yorkshire & Humber     0.21339728

Answer: This model has the following interpretations:

The estimate fo Year is the negative binomial regression estimate for a one unit increase in year. Assuming that each "unit" is 1 year then for each additional year, the difference in the logs of expected number of jobs is expected to decrease by -0.13369, exponentiating this gives 0.875 which means that overall there is a 12.5% decreasee in jobs for every 1 year increase

You can add in the intercept and random effects to obtain individual estimates for each region - as you did - however these will be shrunken due to partial pooling. Also, note that your formula
exp(Intercept + Year*2 + London_intercept) = exp(0.23290 + -0.13369*2 + 0.42820729) = 1.482496 means that there is a 48% increase in jobs associated with a 2 year increase in Year

If you want unshrunken estimates then you should fit fixed effects for Year

It is common in models such as these to have a nonlinear association with time, so you might want to consider adding an additional nonlinear term (eg quadratic) or using splines. If using the former it may be best to centre the Year variable first.

Another possibility is to allow for the "effect"of Year to vary by region, by fitting random slopes:

    Jobs ~ 1 + Year + (Year | Region)


i try to add value array in array using push(),but i dont know how to add it

Question: this mycode, I try to value in company1 staff, but it create a new list of array. can someone help me?
after I add the name and id of staff the array  will look like this

[{companyName: "company1",companyAddress: "company address",staff:
  [{name:"men",id: "123"},{name:"boy",id: "1343"},{name:"john",id:
  "145"}]}]

    <input type="text" ng-model="nameStaff" />
    <input type="text" ng-model="idStaff" />
    <button ng-click=addDetail()>add</button>
    {{form}}

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.form = [{ companyName: "company1", companyAddress: "company address", staff: [{ name: "men", id: "123" }] }];
    $scope.addDetail = function() {
        $scope.form.push({ staff: [{ name: $scope.nameStaff, id: $scope.idStaff }] });
    }
}

Answer: You're pushing on to the form, but you want to push on to the staff of the first object in the form:
$scope.form[0].staff.push({
  name: $scope.nameStaff,
  id: $scope.idStaff
});

Comment: closing bracket is missing in above $scope.form[0].staff.push({
  name: $scope.nameStaff,
  id: $scope.idStaff
});


Is there any cmd callback?

Question: Obviously I can execute something with cmd console using Process.Start();
Is there any way to get output of that process? For example, I could have something like...
Process.Start("sample.bat");

... in my C# winforms application and sample.bat will contain something like:
echo sample loaded

First Question: is there any way to retrieve that sample loaded, after bat execution?
Second question: is there a way to use it without popped up console window?
Comment: See http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
Comment: And see http://stackoverflow.com/questions/7459397/how-to-easily-run-shell-commands-using-c
Comment: only ask one question in each post
Comment: possible duplicate of [Process.start: how to get the output?](http://stackoverflow.com/questions/4291912/process-start-how-to-get-the-output)
Answer: There is an example of exactly how to do this in the Process documentation:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

Answer: Yes, you can use
Process.Start(ProcessStartInfo)
There are a few ways to hook into I/O including ProcessStartInfo.RedirectStandardOutput available.  You can use these overloads to read output from your batch files.  You can also hook into the Exited event to know when execution is complete.
Use CreateNoWindow for no window.
Answer: Set process.StartInfo.RedirectStandardOutput to true and subscribe to process.OutputDataReceived
using (var process = new Process())
{
    process.StartInfo = new ProcessStartInfo("exename");
    process.StartInfo.RedirectStandardOutput = true;

    process.OutputDataReceived += (s, ev) =>
    {
        string output = ev.Data;
    };

    process.Start();
    process.BeginOutputReadLine();
    process.WaitForExit();
}

Is there any cmd callback?


R built-in Breusch-Pagan Test getting different results from manual Calculation

Question: I was using the following code to calculate the bp-test (eaef.csv can be found here).
student.dat <- read.csv("eaef.csv", header=T, sep=",")
attach(student.dat)
lnearnings <- log(earnings) ; weightsq <- weight^2
student.lm2 <- lm(lnearnings~schooling+height+weight+weightsq, student.dat)
bptest(student.lm2,~schooling*height*weight*weightsq+
         I(schooling^2)+I(height^2)+I(weight^2)+I(weightsq^2))

the output is:
data:  student.lm2
BP = 20.338, df = 18, p-value = 0.3141

However, if I construct the test manually:
#direct construction of bptest
aux.lm <- lm(I(residuals(student.lm2)^2)~ schooling*height*weight*weightsq+
               I(schooling^2)+I(height^2)+I(weight^2)+I(weightsq^2))
pchisq(nrow(student.dat) * summary(aux.lm)$r.squared, 19, lower.tail=F)

I got different p-value 0.3745022.
The way I construct the manual test is by following the definitions in this slide (page 38).
Any idea why is there a difference?
Answer: You used 19 degrees of freedom while bptest() used only 18. The reason for this discrepancy is that you cannot include the identical regressors weightsq and I(weight^2) in the auxiliary regression. Well, you can, obviously, but only one coefficient can be estimated while the other is aliased and set to NA:
R> coef(aux.lm)[c("weightsq", "I(weight^2)")]
##    weightsq I(weight^2)
## 0.005487211          NA

Thus, using the degrees of freedom only from the non-aliased coefficients gives the same results as bptest():
pchisq(nrow(student.dat) * summary(aux.lm)$r.squared,
  sum(!summary(aux.lm)$aliased) - 1, lower.tail = FALSE)
## [1] 0.3141148


How can I move Git lfs Storage from Artifactory to Github

Question: I want to move my Git lfs storage (one Git lfs repo in artifactory) with all its content to Github lfs as I want to migrate from Artifactory. My code repositories reside in Github as well hence I want to keep lfs storage in the same location.
I would like to know if lfs storage can be either moved or exported to any other storage provider. In this case Artifactory to Github.
Answer: The query is confusing. Artifactory and Github functionalities are completely different.
GitHub is a centralised place or tool that is used to save your source code.(example .java, .c++ etc). It's a source code manager.
Artifactory is a place where you save your installable binaries. (example .war, .ear, .nuget package etc). It's a binary manager.
Can you elaborate a bit on your query.
Comment: When tracking lfs with github (without configuring other binary managers for lfs ) files are getting saved into https://github.com///info/lfs. That is Git lfs. Which also don't need to have .lfsconfig. Maybe what I have mentioned as Github lfs confused you.
My requirement is to change the current lfs tracking which is using artifactory to be tracked in git lfs. So that finally I don't need to have an artifactory connection.


Secure channel trust verification fails

Question: Working on an issue with setting up a trust between two domains with several firewalls in between, and a pinhole routing between two servers in them.
newdc.newdomain.com is a 2012 server in a brand new domain.
admt.olddomain.local is a 2008R2 server in an existing domain, with two existing domain controllers dc1.olddomain.local and dc2.olddomain.local This server will be used for, as you might have guessed, Active Directory Migration Tool (ADMT)
There are firewall rules in place to allow newdc.newdomain.com to talk Active Directory only to admt.olddomain.local both ways. All DNS tests are fine, as are DCDIAGs on both sides.
When creating the trust on admt.olddomain.local I got the following error

The incoming trust has been verified. It is in place and active.
The verification of the outgoing trust failed with the following error(s):
The trust password verification test was inconclusive.
A secure channel reset will be attempted.
The secure channel reset failed with error 1311: There are currently no logon servers available to service the logon request.

The trusts were however created, incoming and outgoing, in both domains. Validating the trust (both ways) on newdc.newdomain.com comes back as verified successfully. However when I attempt to validate the trust from server admt.olddomain.local I get the following error:

The secure channel (SC) reset on Active Directory Domain Controller \dc1.olddomain.local of domain olddomain.local to domain newdomain.com failed with error: There are currently no logon servers available to service the logon request.
The incoming trust was successfully validated.

I can see the issue here, even though I'm performing the validation from admt.olddomain.local it actually attempts to check the secure channel from dc1.olddomain.local which can not communicate with the server newdc.newdomain.com, but is it really an issue? Is there any way to force the validation to take place from admt.olddomain.local? Will we be able to use ADMT with this setup? (we're going to try a test copy using it soon, just to see what happens in the current setup)
Eventually we're going to rebuild this admt.olddomain.local server into a Read Only domain controller for newdomain.com using the same network address and firewall config/network routing, and it will be the only machine able to communicate with dc01.olddomain.local and dc02.olddomain.local, but will we have the same issue since newdc.newdomain.com can't directly route to either dc01/dc02 to verify trust?
Thanks for any input on this!
Answer: OK so here is what we ended up doing, rebuilding the AD structure so the newdomain.com had an ADMT/DC server on the same network as olddomain.com AD servers, then transfering FSMO roles to the new domain server so that the two domains could talk dircetly between the FSMO Masters without all the intervening firewalls messing things up. If you've got everything worked out for DNS, firewalls, etc, and are still getting errors, start looking at if the FSMO role masters can talk to each other directly!

Secure channel trust verification fails


Proof of Big O notation example

Question: I am a beginner and taking an online algorithm course, and when I referred to a book, I found the following question.

Given that $f(x) = 2x^2 + 5x +3$ and $g(x) = 2x^3 +x -100$, prove $f(x) = O(g(x))$

I know that to prove $f(x) = O(g(x))$, I have to show that there are some positive constants $c$ and $x_{min}$ for which if $x\ge x_{min}$ then $f(x)\le c \cdot g(x)$.
I tried the following:

Let c = 4 and x = 5.
  I want to prove that $2x^2 + 5x + 3 \le c(2x^3 + x - 100)$.
  I tried to solve the left side as follows:
  If $x \ge 1$, then $x^2 \le x^3$ and $5x \le 5x^3$ and $3 \le 3x^3$.
  So $2x^2 + 5x + 3 \le 2x^3 + 5x^3 + 3x^3$
  $\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;= 10x^3$

My question is can I ignore the $-100$ of $g(x)$ and compare it with $10x^3$ for some value of $c$?
Thanks for any explanation.
Comment: Welcome to Maths SX! I suppose this is when $x\to\infty$?
Comment: @Bernard yes as x grows faster.
Comment: The purpose of this exercise is to help you understand how to _prove_ a simple example of "big-O" notation, so no, you cannot ignore the -100. You should not "try to solve the left side" -- instead, you should try to show that when $x$ is large enough, the inequality will be true. So you should use $x>5$, not $x=5$. Setting $c=4$ and subtracting the left from the right, can you show that $0<8x^3−2x^2-x−403$ when $x>5$? Hint: If you rewrite it as $0<(2x^3-2x^2)+(x^3-x)+(5x^3-403)$, then you can see that each term on the right is positive.
Answer: Hint:
Use equivalence:
$$f(x)\sim_\infty 2x^2,\qquad g(x)\sim_\infty 2x^3,\quad\text{ so }\quad\frac{f(x)}{g(x)}\sim_\infty\dots$$
Comment: Thanks for the explanation but if what if I am asked to prove f(x) = O(g(x))? Do I need to ignore the x-100 (every term except the fastest growing term)?
Comment: This proves  a stronger result: $f(x)=o\bigl(g(x)\bigr)$. I think you're  supposed to know a polynomial is asymptotically equivalent to its leading term. So we don't have to care for the other terms.

Proof of Big O notation example


Apple Pay. Workflow

Question: I don't clearly understand - how Apple Pay works in case of online checkout via online store.
From my understanding:
  Prerequisites:
    1) Card which will be used for payment should be added to Passbook.
    2) During adding this card to passbook Apple device sends request with PAN to issuer and if verification is passed - format unique token, which is stored in AppleSecurity element.
When customer try to make purchase online via online store: 1) customer should switch the card, which will be used for payment  2) Store formats the request with total amount, shipping address and token, which is stored on Security element 3) Apple device sends request to AppleServer for payment authorization  4) After this store can executes additional logic (whatever)
Feel free to correct me if I'm wrong.
But my question is - if existing system already uses tokenization service, payment gateway and payment processor - how it can be integrated with Apple Pay?
Answer: You need to look at the documentation on Apple. Your description of the way apple pay works is correct in the first part, and incorrect in the second part. There's a good tutorial on Apple Pay at Ray Wenderlich.com that shows how to implement it.
Here's a general description:
Within an app, Apple Pay is just a source for payment details. The app is responsible for

creating a payment request (with line items and a total)
triggering the apple pay interface
checking any shipping details
contacting the back end or a service (Stripe, etc) to create a token for the specific purchase
sending the successful purchase token to the app's server to record the purchase

So there are two tokens needed:  one for the user's payment details (the card) and a second token for the actual purchase. In loose terms, Apple Pay is responsible for generating the first one, but the app + some service is responsible for generating the second one.

Apple Pay. Workflow


Bat file para rodar arquivo.r

Question: Gostaria de usar um arquivo .bat para rodar determinado arquivo.r diariamente com o taskmanager do windows, mas não estou conseguindo fazê-lo rodar.
Meus passos:
1) abrir notepad
2) digitar código, que atualmente é:
"C:\Program Files\R\R-3.3.0\bin\i386\Rscript.exe" --vanilla  "G:\Macroeconomia\Economistas\Coleta\Prohort\Prohort.R"

3) salvar o arquivo em formato .bat
4) dois cliques para rodá-lo
Entretanto o bat não roda inteiro, ele só carrega os pacotes do meu código e fecha.
Comment: Por padrão, o Windows fecha o terminal quando algum script termina de rodar. Eu recomendo entrar no terminal, navegar até onde o arquivo `Prohort.R` está (i.e., o diretório específico dentro do drive G:) e rodar `"C:\Program Files\R\R-3.3.0\bin\i386\Rscript.exe" CMD BATCH Prohort.R`. Isto vai gerar um arquivo `Prohort.Rout` e dentro dele vai estar o log do R. Aí vai ser possível ver o que deu errado no teu script. Ou seja, descobrir porque ele está apenas carregando os pacotes, sem rodar mais nada.
Comment: O que você quer dizer com "ele só carrega os pacotes do meu código e fecha"?
Comment: O início do meu código de R é uma função que carrega todos os pacotes necessários para rodar o código, então quando eu rodo o bat, dá pra ver "loading packages", aí então fecha
Comment: Se ele fecha, é por que terminou a execução. Coloque um `pause` na lina abaixo, da sua.
Comment: mas ele não está executando até o final, tanto que os arquivos que ele gera não estão sendo atualizados
Answer: Como falado pelo colega Marcos Nunes:
Por padrão, o Windows fecha o terminal quando algum script termina de rodar. Eu recomendo entrar no terminal, navegar até onde o arquivo Prohort.R está (i.e., o diretório específico dentro do drive G:) e rodar "C:\Program Files\R\R-3.3.0\bin\i386\R.exe" CMD BATCH Prohort.R. Isto vai gerar um arquivo Prohort.Rout e dentro dele vai estar o log do R. Aí vai ser possível ver o que deu errado no teu script. Ou seja, descobrir porque ele está apenas carregando os pacotes, sem rodar mais nada.
Assim, abrindo o arquivo .Rout como bloco de notas consegui visualizar o crash!
Answer: @Danilo Imbimbo, fiz um script no R, que carrega pacotes e executa algumas tarefas também. Respondendo sua pergunta, quando você executa seu *.bat ele abre o cmd e fecha e você não vê nada por que provavelmente você não coloca nenhuma função no script que salva algum arquivo ou imagem. Se você cria um script que só gera objetos dentro do ambiente R, mas não usa nenhuma função para exportar os resultados para fora do ambiente R, você não verá os resultados (acredito que você queria ver as saídas do R, em algum lugar). Então você precisa editar seu script e colocar algumas funções como "write.table()" para salvar alguns objetos e por aí vai. O que você fez seria como se você abrisse o R, rodasse a análise e fechasse o R sem salvar nada.

Bat file para rodar arquivo.r


Good practices for AES key derivation and storage on STM32

Question: I'm developing a device on STM32L4x6. It is connected through BLE to a smartphone and it exchanges encrypted data with it.
Encryption is AES-GCM and I'm using the reference implementation provided by STMicro.
I have implemented a shared secret exchange mechanism using Diffie-Hellman protocol on Curve25519. Right now I am using this shared secret directly as AES key.
However I am confused on 2 points:

I think I have to derive a session key from the shared key however I don't really understand how.
about key storage on STM32, what is the common/best practice ? Is it enough to store the key in Flash and to set the Flash in Read Protected Level 1 ?

Thank you
Answer: As for deriving a session key - you may want to look into the topic of Key Derivation Function (KDF). Googling it returns a lot of useful informations related to establishing session keys. You may also ask your question on https://crypto.stackexchange.com/.
As for storing keys in STM32 - it depends what your requirements are. Do the keys need to persist between sessions or can you generate a new one each time a connection is established? Generating a new key each time a new connection is made will be safer due to two reasons:

It's different for each connection so even if someone manages to get the key for a session from the past, it may only be used to decrypt that session.
If you generate a new key for each new session, you don't have the need to store it anywhere such as Flash memory, as you may keep it in RAM only. Powering down the device will wipe the key. Enabling read protection prevents access to RAM as well as to internal Flash.

Regarding 2nd point however - STM32 is NOT considered a "Secure Microcontroller". It lacks hardware elements that prevent hardware attacks - power voltage glitch detection, side-channel prevention, secure mesh etc. With enough resources and determination an attacker will be able to obtain the cryptographic keys that you use, for example by grinding down the chip package and optically reading your data. That touches on the aspect of how secure does the device really have to be - development time cost, hardware security cost. With STM32 all you can do is to make it harder (keep the keys in RAM and only when you need it, then overwrite them with noise) and limit the scope of the attacker (change session keys as often as possible, e.g. each session).


Solving ODE, with sinusoidal force and harmonic oscillator

Question: OK, this is another one of those that should be simple enough to do. But maybe I am just bad at differential equations.
We have the following:
$$x''+ \gamma x'+ \omega_0^2 = 3 \cos t + 2 \sin t$$
Now, if this was just $x''+ \gamma x'+ \omega_0^2 = 3 \cos t$ I would start with a solution that took the form from the roots of the characteristic equation, which in this case is $r^2 + \gamma r + \omega_0^2$ and the roots are $\frac{-\gamma \pm \sqrt{\gamma^2 - 4 \omega_0^2}}{2}$. If the root is imaginary the solution would be
$y=C_1e^{\frac{-\gamma}{2} t} \cos \frac{\sqrt{\gamma^2 - 4 \omega_0^2}}{2}t + C_2e^{\frac{-\gamma}{2} t} \sin \frac{\sqrt{\gamma^2 - 4 \omega_0^2}}{2}t$
and if the roots are real the solution would look like $x=C_1 e^{\frac{\sqrt{\gamma^2 - 4 \omega_0^2}}{2}t}+C_2e^{\frac{\sqrt{\gamma^2 - 4 \omega_0^2}}{2}t}$.
Or we might go with taking $x_p$, a particular solution, and going with $x_p = A \sin t + B \cos t$.
I wasn't sure how to go tho, and I am sure the latter solution is the one, but I wanted to check. I know this may sound simple enough to most people here, but I am stil feeling my way through differentials a bit.
Answer: Actually, your homogeneous solution should be
$$x=C_1e^{\frac{-\gamma}{2} t} \cos \frac{\sqrt{4 \omega_0^2-\gamma^2 }}{2}t + C_2e^{\frac{-\gamma}{2} t} \sin \frac{\sqrt{4 \omega_0^2-\gamma^2 }}{2}t$$
The particular solution is, as you say, of the form $A \cos{t} + B \sin{t}$.  Plug this into the equation to get
$$-(A \cos{t} + B \sin{t}) + \gamma (-A \sin{t}+B \cos{t}) + \omega_0^2 (A \cos{t} + B \sin{t}) = 0$$
or
$$[(\omega_0^2-1) A + \gamma B] \cos{t} + [-\gamma A + (\omega_0^2-1) B] \sin{t} = 3 \cos{t} + 2 \sin{t}$$
which means that
$$(\omega_0^2-1) A + \gamma B=3$$
$$-\gamma A + (\omega_0^2-1) B = 2$$
Solve for $A$ and $B$.
Comment: Thanks! That was really stupid of me.
Comment: Btw I was just curious, why switch the terms under the square root?
Comment: Because you're using trigonometric functions, not exponentials. You write it yourself: *`If the root is imaginary the solution would be [...]'* You only make one mistake: what's underneath the square root should be *minus* the discriminant or else it's still negative and the root imaginary. Look up this fine point again in your book.
Comment: so you multiply what wold be the $b^2 - 4ac$ of the quadratic by -1, yes? I didn't see that bit anywhere i my text but I will look.


C trying to understand select() and FD_ISSET()

Question: Im trying to make a basic non blocking chat client, but i cant really understand select() and FD_ISSET(). im trying to listen to the socket with the code below, but it wont work, it doesn't print anything, why not?
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(int argc, char const* argv[])
{
   fd_set readfs;
   char sendline[100];
   char str[100];
   char *some_addr;
   int listen_fd, comm_fd;

   struct sockaddr_in servaddr;

   listen_fd = socket(AF_INET, SOCK_STREAM, 0);

   //Socket error
   if (listen_fd == -1) {
      printf("Error on getting socket, Exiting!\n");
      return 1;
   }
   bzero(&servaddr, sizeof(servaddr));

   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr = htons(INADDR_ANY);
   servaddr.sin_port=htons(22000);

   bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));

   listen(listen_fd, 10);

   comm_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);

   FD_ZERO(&readfs);
   FD_SET(comm_fd, &readfs);

   while (1)
   {
      select(listen_fd,&readfs, NULL, NULL, NULL);
      if(FD_ISSET(listen_fd,&readfs))
      {
         bzero(str,100);
         read(listen_fd,str,100);
         printf("%s", str);
         /* write(listen_fd, "read!", strlen(str)+1); */
      }
   }
   return 0;
}

EDIT:
My code trying to Connect to the server:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include<string.h>

int main(int argc,char **argv)
{
    int sockfd,n;
    char sendline[100];
    char recvline[100];
    struct sockaddr_in servaddr;

    sockfd=socket(AF_INET,SOCK_STREAM,0);
    bzero(&servaddr,sizeof servaddr);

    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(22000);

    inet_pton(AF_INET,"127.0.0.1",&(servaddr.sin_addr));

    connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

    while(1)
    {
        bzero( sendline, 100);
        bzero( recvline, 100);
        fgets(sendline,100,stdin); /*stdin = 0 , for standard input */

        write(sockfd,sendline,strlen(sendline)+1);
        read(sockfd,recvline,100);
        printf("%s\n",recvline);
    }

    return 0;
}

Comment: The first argument to `select()` should be your highest file descriptor *plus one*. So if you only have one, here, it should be `listen_fd + 1`. Also, `bzero()` is ancient, you should be migrating to `memset()`. Presumably you have another process that is actually writing to your socket? Further, looks like you should be using `comm_fd` in your `select()` call and loop, and not `listen_fd` at all. If you `select()` on `listen_fd`, it'll return when there is an  `accept()`able connection available, not when there is input ready on your already connected socket.
Comment: For one thing, you aren't checking for a single error from any of `socket()`, `bind()`, `listen(),` `select(),` or `accept().`
Comment: yes ive edited in it, and ive tried listen_fd+1 but it dosent work :(
EDIT: Changing to comm_fd made it work, but only the first thing i type in.
Comment: You client code is just as bad. After each of `socket(),` `bind(),` `connect()`, `read()`, and `write()`, you must check the result for -1, and if so call `perror()` and stop processing. In addition, if `read()` or `recv()` returns zero you must stop reading, close the socket, and stop processing; and if it returns a positive number you must only use that many bytes of the buffer you read into.
Comment: Problem Solved. Thanks Paul Griffiths!
Comment: @EJP how do i check if read or recv retruned 0?
Comment: The same way you check any other return value of any other function.
Answer: Four major problems, here:

Your select() call and the read/write loop should be using comm_fd, not listen_fd. If you call select() on listen_fd it'll return when there is an accept()able connection available, but you want to wait on the connected socket you already have for input, so use comm_fd.
The first argument to select() should be the highest file descriptor in the sets plus one. Since you only have one file descriptor, here, it should be comm_fd + 1.
You should move your FD_ZERO and FD_SET macros inside the while loop, and execute them prior to every select() call, because select() is going to modify those fd sets you pass to it.
You don't check the return from your system calls for errors. You should.

Other points:

bzero() has been removed from POSIX for quite some time, now, you should be using the standard memset() instead.
You shouldn't pass INADDR_ANY though htons(), just use it as it is.
It's only a comment in your program, but while STDIN_FILENO may be 0, stdin is a FILE pointer, and is not 0.
Answer:

but i cant really understand select() and FD_ISSET()

An fd_set is like a bit array. Each bit in the array represents a socket or file descriptor.
FD_ISSET() is a macro or function that tells you whether a given socket descriptor (4, for example) is set in the bit array (fd_set). FD_SET() allows you to set a bit yourself, and FD_CLR() lets you clear a bit.
The bits don't just get set magically, you use select() to ask the OS kernel to set or clear each bit in the fd_set accordingly, then you check each bit with FD_ISSET() and act accordingly. Before calling select() you must setup the sets to tell the kernel which descriptors you are interested in polling by setting the bits in the fd_set using FD_SET() or if you have lots of sockets/bits to set, using a master fd_set and copying the whole thing to your read, write or error set. I usually did the latter for efficiency. These are integers typically from 0 to N (first 3 are usually not sockets so you normally poll 3 .. N). After select returns, you must check the bits. If a bit is set in readfds it is ready for reading.
select(int nfds, fd_set *readfds, fd_set *writefds,
              fd_set *exceptfds, struct timeval *timeout);

The supported statuses are "ready for read", "ready for write", and "error condition"
If you don't set a particular bit in the set, the kernel won't report its status to you.
As well, if you don't set the nfds param (max descriptor value) high enough, any descriptors above the max will be ignored. The descriptors do not have to be contiguous, just within the range of nfds.
All of this logic assumes successful return values on the system calls. If a system call returns an error status, you don't even regard the data structures for that call and must recover or process appropriately.
The primary problem that jumps out at me in your code is your select call's first argument. It isn't going to check comm_fd is comm_fd is lower than listen_fd.
I recommend you keep an int value of max_desc and each each time you accept a new socket, set max_desc = MAX(max_desc, new_fd+1), as well, you'll need to adjust it downward when closing out sockets. I always prefer to keep a separate fd_set just to track the descriptors my process has open (never pass it to select() just use it for bookkeeping).
Answer: Came across this ... better late than never, I guess.
If I could add to 'mrjoltcola's responses ... perhaps a good way to describe the 'select()' statement is that it's a DE-MULTIPLEXER of I/O devices.  You can ask the O/S to simultaneously watch socket-descriptors and file-descriptors from multiple sources.  When they're interrupted, the O/S will notify the application which devices were triggered/interrupted.
In the case of sockets, an application can have the O/S watch a 'listening' socket as well as several already-connected client sockets.  The application can respond to message traffic from clients ... accept new client connections ... or drop/disconnect clients that have terminated.
That said, here's the SERVER code with 'mrjoltcola's fixes for:

(1) select on 'comm_fd'
(2) nfds + 1
(3) FZ_ZERO and FD_SET on each iteration
(6) No byte-swap on INADDRANY (it's 0.0.0.0, so no need)

My bad, but I did not implement

(4) error checking
(5) memset() instead of bzero()

Also, I replaced the 'read()' and 'write()' operations with 'recv()' and 'send()', respectively.  They're semantically the same because the 'flags' option is set to 0.  But in some applications the 'flags' parameters might be helpful.
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>

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

   int    nfds = 0;

   char str[100];
   int listen_fd, comm_fd;

   struct sockaddr_in servaddr;

   printf("---> Begin Server:\n");

   listen_fd = socket(AF_INET, SOCK_STREAM, 0);

   //Socket error
   if (listen_fd == -1) {
      printf("Error on getting socket, Exiting!\n");
      return 1;
   }
   bzero(&servaddr, sizeof(servaddr));

   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr = INADDR_ANY;
   servaddr.sin_port=htons(22000);

   printf("---> Bind listening socket to port: %hd\n",
          ntohs(servaddr.sin_port));

   bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));

   printf("---> Listen for connection request\n");

   listen(listen_fd, 10);

   printf("---> Accept connection request\n");

   comm_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);

   while (1)
   {
      FD_ZERO(&readfs);
      FD_SET(comm_fd, &readfs);

      nfds = comm_fd + 1;

      printf("---> Wait for message\n");

      select(nfds, &readfs, NULL, NULL, NULL);

      if(FD_ISSET(comm_fd,&readfs))
      {
         printf("---> Received message\n");

         bzero(str,100);
         recv(comm_fd,str,100, 0);

         printf("---> Received Msg: %s", str);

         printf("---> Send reply\n");

         send(comm_fd, "read!", strlen(str)+1, 0);
      }
   }

   return 0;
}

/* EOF */

And the CLIENT code is:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc,char **argv)
{
    int sockfd;
    char sendline[100];
    char recvline[100];
    struct sockaddr_in servaddr;

    printf("---> Begin Client\n");

    sockfd=socket(AF_INET,SOCK_STREAM,0);

    bzero(&servaddr,sizeof servaddr);

    servaddr.sin_family=AF_INET;
    servaddr.sin_port=htons(22000);

    inet_pton(AF_INET,"127.0.0.1",&(servaddr.sin_addr));

    printf("---> Connect to svr:\n"
           "--->    port...: %hd\n",
           ntohs(servaddr.sin_port));

    connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

    while(1)
    {
        bzero( sendline, 100);
        bzero( recvline, 100);

        printf("---> Enter message:\n");

        fgets(sendline,100,stdin); /*stdin = 0 , for standard input */

        printf("---> Sending: %s\n",
               sendline);

        send(sockfd, sendline, strlen(sendline)+1, 0);

        printf("---> Receive reply\n");

        recv(sockfd,recvline,100, 0);

        printf("---> Reply: %s\n",recvline);
    }

    return 0;
}

/* EOF */

These compiled/linked/ran on my little CentOS laptop ... gcc ... etc.
By the way, if you ever find yourself using 'select()' on a Windows node, the 'nfds' argument is 0.  Microsoft didn't fully comply with the original BSD sockets interface.  Their implementation ('under-the-hood') is different, but the behavior is the same ... to de-multiplex I/O from multiple devices for reading/writing/errors.
Comment: `bzero()/memset()` isn't required at all in properly coded network programming. All you have to do is use the length returned by `recv()/read()` correctly, instead of assuming the read filled the buffer.


Publication bias in meta-analysis of diagnostic accuracy in R?

Question: Are there any implemented methods in R that could be used to assess publication bias in a meta-analysis of diagnostic accuracy (Egger's test, funnel plots)?
One way would be to change sensitivites and specifities to log diagnostic odds ratios (logDOR), run meta-analysis on the logDOR using common rfx-models and then e.g. use funnel() and regtest() from the metafor package. However as I understand the bivariate approach (Reitsma et al., 2005) is to be prefered. But if a run a bivariate linear model, how can I assess publication bias?
<code>library(mada)
data(Dementia)
(fit <- reitsma(Dementia))
summary(fit)
</code>
Comment: I'm not an expert on the topic, but from what I have heard from experts in the field is that these tests don't work for reviews of diagnostic accuracy testing and that new methods are currently being developed. I would suggest you check out the guidance from the Cochrane Collaboration. Will update my post if I find anything conclusive.
Answer: There is an older paper of Deeks et al justifying the use of the diagnostic odds ratio for this purpose:
on this method:
http://www.ncbi.nlm.nih.gov/pubmed/16085191
The work of Deeks et al is not related to the bivariate model. From my limited experience I can nevertheless recommend this approach.
Answer: Check out the Meta-Analysis Task View
Comment: Could not find anything regarding publication bias in the mentioned packages for diagnostic accuracy: mada, HSROC, metamisc, bamdit...


Oracle VM vs Xen Server

Question: We were considering using Xen Server. We came across oracle vm which seem like has more features. Would anyone recommand which product might be better?
Seem like oracle vm comes with some options you have to pay for from Xen Server and is based off of Xen.
Anyone know?
Thanks
Answer: We use Xen itself and not a derivative of it like Oracle VM and Citrix XenServer.  Xen is less "user friendly" but has the broadest range of features available and nearly everything for it is free whereas you have to pay for most of that stuff with the commercial derivs.  We are extremely happy with Xen and would not seriously consider the derivs after having used it.
Answer: Since both Oracle VM and Xenserver, use the XEN hypervisor under the hood, the main differences are going to be in the management tools and support. If you use any other Oracle tools, then I would say that you should stick with Oracle for support reasons. If you use Citrix in-house, then go with Xenserver.
Otherwise, compare the features of the management tools and see if there is anything there that would guide your choice.
In either case your virtual machines will get the same virtualization facility under the hood. Only your admin and ops people will notice a difference.
Answer: We're using both, and they are not all that different when it comes to features. Notably, Oracle supports PVM for Windows guests, and can be managed from within Oracle Enterprise Manager.
If you are planning to run Oracle databases you may want to go with Oracle VM to avoid licensing issues (such as having to buy a database license for every cpu in the cluster) and to have a single point for support.
edit> There's one significant difference, come to think of it; The management tools for Oracle VM does not support snapshots, although you can probably work something out on the storage level (LVM, NAS or SAN).

Oracle VM vs Xen Server


Need to add sequentional data rows

Question: I have a table with 2 columns. In the first column I have a counter to 30,000. In the second column I would like to add to 2nd column the rows '1-30000' to test for a conversion.
I am trying to make it look like this
COL A      Col B
1          1-1
2          1-2
3          1-3

I am a newbie at this and no matter how I try I can get the first row to do my bidding but the Col B starts its row at the end of Col A
Comment: Are you looking for string concatenation? `CONCAT(ColA, '-', ColB)`?
Comment: Can you show your working so far pls.
Comment: Can you be more specific?  your requested output data looks like you just want to add '1-' to ColA
Comment: Is ColB an integer or a string?
Answer: I don't know what is your RDBMS, but you can try:
update table
set colB = colB+'-'+colA

Need to add sequentional data rows


How to Fetch query result 1 time from each starting alphabate

Question: The question's heading may confuse you so please allow me to explain it here. I'm currently hosting a pin code search website of India. In a mysql query, I'm trying 20 post offices of a state. I want every single query result should start from a unique alphabate, i.e. the first result should show the result of a post office starting from alphabet A, the second result should show the post office name starting from alphabet B and so on till the 20th record as given below :
Anand Vihar
Bangla Sahib
Connaught Place
Delhi Haat
Eshwar Colony
Friends Colony
Gitanajali Enclave
Harish Nagar
Indira Colony
Jangpura
Karol Bagh.... till the 20th record starting with unique alphabet initial.
Below is the current query I'm using :-
<code>$sql="SELECT `states`, `districts`, `pincodes`, `postoffices`, count(`postoffices`) as totcount
    FROM `table_pins` WHERE `states`='$state'
    group by `postoffices`
    LIMIT 20";

$result = mysqli_query($con,$sql);
$rowcount=mysqli_num_rows($result);
</code>
Answer: I believe you want to group by first letter. Here is one way of doing it
<code>select substr(postoffices,1,1) as alphabet
from table_pins
group by substr(postoffices,1,1)
</code>
you can check similar answers here
Comment: I want to group by first letter but for list of post offices not in the state, Will this code work for post offices?