Write to file instead of stdout

Question: I am writing a program in C.This program prints out the files present in current directory.
I want the output in some text file not on the console.
my program is:-
int main()
{

        system("ls");
        return 0;
}

Thanks in advance!!!
Comment: Well one way is while executing in the terminal just do `./xyz > logfile.txt`
Answer: Since you're already using system(), and this is already platform-dependent, just use the shell's redirection capability -- i.e.,
system("ls > /home/you/thefile");

Comment: I agree this is easier than fopen(), but it is not exactly the canonical example of how to write to a file in C. -1.
Answer: This is how you write to a file, just replace your output with what you want in the file.
As the other person mentions you could just pipe it to a file.
FILE *ofp;
char outputFilename[] = "out.txt";

ofp = fopen(outputFilename, "w");

if (ofp == NULL) {
  fprintf(stderr, "Can't open output file %s!\n",
          outputFilename);
  exit(1);
}

fprintf(ofp, "ls");
fclose(ofp);

Answer: There is a another function to redirect stdout to a file
###stdio.h
###FILE *freopen(const char *filename, const char *mode, FILE *stream);

    int main()
    {
      char outputFilename[] = "out.txt";
      freopen(filename, "w", stdout)

        system("ls");
        return 0;
    }

All the output to stdout after redirecting will be written to file "out.txt"

Write to file instead of stdout


Py.test collection phase taking very long

Question: I am really quite new to development in Python in general, let alone testing with pytest. My problem is that the pytest collection phase runs unusually slow. I am specifying the test directory which contains only a handful of files with only one file containing three tests. The collection takes pretty much a whole minute, after which the actual tests run in under a few seconds. I have looked at similar questions but couldn't find a solution. I don't think it matters (as py.test is slow even from the command line) but I am using the pycharm IDE. The OS is Ubuntu.
This may be relevant: If I terminate the process after a few seconds I usually end up with a stacktrace ending as follows:

File "/usr/local/lib/python2.7/dist-packages/_pytest/core.py", line 413, in __call__
    return self._docall(methods, kwargs)
  File "/usr/local/lib/python2.7/dist-packages/_pytest/core.py", line 424, in _docall
    res = mc.execute()
  File "/usr/local/lib/python2.7/dist-packages/_pytest/core.py", line 315, in execute
    res = method(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/_pytest/helpconfig.py", line 27, in pytest_cmdline_parse
    config = __multicall__.execute()
  File "/usr/local/lib/python2.7/dist-packages/_pytest/core.py", line 315, in execute
    res = method(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 636, in pytest_cmdline_parse
    self.parse(args)
  File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 747, in parse
    self._preparse(args)
  File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 709, in _preparse
    self._initini(args)
  File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 704, in _initini
    self.inicfg = getcfg(args, ["pytest.ini", "tox.ini", "setup.cfg"])
  File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 861, in getcfg
    if exists(p):
  File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 848, in exists
    return path.check()
  File "/usr/local/lib/python2.7/dist-packages/py/_path/local.py", line 352, in check
    return exists(self.strpath)
  File "/usr/lib/python2.7/genericpath.py", line 18, in exists
    os.stat(path)
KeyboardInterrupt

Or sometimes...
<STACK TRACE...>
  File "/usr/local/lib/python2.7/dist-packages/py/_iniconfig.py", line 50, in __init__
    f = open(self.path)
KeyboardInterrupt

Maybe one of the two last calls before the KeyboardInterrupt is very slow?
Please do ask for more detail should you require it!
Cheers!
Comment: Going by that stacktrace it's trying to find the project root.  Could you show the layout of the files in your project and also show the exact py.test command you invoke as well as which directory you invoke this from?
Comment: > This may be relevant: If I terminate the process after a few seconds ... Yes, I think it is relevant. The related question [how to speed up py test](https://stackoverflow.com/questions/16417546/how-to-speed-up-py-test) gives suggestions for how to speed py.test that seem relevant given your stack trace.
Answer: Add PYTHONDONTWRITEBYTECODE=1 to your environment variables!

Windows Batch: set PYTHONDONTWRITEBYTECODE=1
Unix: export PYTHONDONTWRITEBYTECODE=1
subprocess.run: Add keyword env={'PYTHONDONTWRITEBYTECODE': '1'}

Note that the first two options are only valid for your current terminal session.

Here is how I found this out: pytest was being unusably slow from the command line, but working fine from within PyCharm. Copying the PyCharm command into cmd.exe (executes a small helper script) also was unusuably slow. Thus I printed out the environ variables at os.environ and tried it with that -- and it was fast! Then I eliminated each one-by-one.
Comment: I am experiencing the opposite. It runs faster from command line than running pytest in pycharm.  It started after installying cython extensions.
Answer: I had the same problem. My fix was to set the Working directory setting in the Run/Debug Configuration  to the folder where manage.py is located.
Answer: My solution was based off of this answer, where I did pytest dir/to/tests and it skipped the collection step entirely.
Answer: Having a large number of files in a sub-directory can cause slow test collection, even non-Python files like images and PDFs. See this similar question.


Como mostrar uma imagem a cada 5 segundos javascript

Question: Bom a minha dúvida é a seguinte, gostaria de saber, como faria para que o javascript desse um intervalo de 5 segundos antes de editar de imagem.
Meu código:

window.onload = function() {
    if(2>1){
        document.getElementById("imagem").src = "https://placeholdit.imgix.net/~text?txtsize=36&txt=Imagem+1&w=350&h=150";
        document.getElementById("imagem2").src = "https://placeholdit.imgix.net/~text?txtsize=36&txt=Imagem+2&w=350&h=150";
        document.getElementById("imagem3").src = "https://placeholdit.imgix.net/~text?txtsize=36&txt=Imagem+3&w=350&h=150";
    }
}

http://pastebin.com/Bc82kPDt
Ou seja que houvesse um intervalo em cada src de 5 segundos.
Que primeiro o javascript editasse o id "imagem", passado 5 segundos editasse o id "imagem2" etc...
Answer: Você pode realizar isso manipulando os objetos do DOM, removendo a imagem anterior e criando uma nova no lugar.
Javascript

var i = 1;
var id = 'imagem'
// Intervalo em milissegundos (1s == 1000ms)
var milissegundos = 2000; // 5000 = 5 Segundos

// Executa a função a cada intervalo de tempo
var interval = setInterval(function(){

  // Recebe o elemento
  var img = document.getElementById(id);

  i++;

  // Seta o source da nova imagem
  img.setAttribute('src', 'https://placeholdit.imgix.net/~text?txtsize=36&txt=Imagem+'+i+'&w=350&h=150');

}, milissegundos);

jQuery

var i = 1;
var id = '#imagem'
// Intervalo em milissegundos (1s == 1000ms)
var milissegundos = 2000;

// Executa a função a cada intervalo de tempo
var interval = setInterval(function(){
  i++;
  // Seta o source da nova imagem
    $(id).fadeOut(200, function(){
        $(id).attr('src', 'https://placeholdit.imgix.net/~text?txtsize=36&txt=Imagem+'+i+'&w=350&h=150').delay(100).fadeIn(200);
    });

}, milissegundos);

Exemplo de Roleta
Comment: Hmm. Entendi @Gonçalo  Você precisa fazer isso com Javascript puro ou pode usar alguma biblioteca como [jQuery](https://jquery.com)?
Comment: Peço desculpa, mas eu sou bocado novato na área do javascript, diga-m e uma coisa, Se eu quiser adicionar mais imagens a editar id's diferentes como faço?
Comment: Opa @Gonçalo, quais são os dados que você tem? Você tem um array com as imagens? Quantas imagens queres adicionar por vez?
Comment: Bom vou tentar explicar direitinho, funciona da seguinte forma: Eu tenho um img de amarelo claro, um img de verde claro, um img, de laranja claro, um img roxo claro e um img vermelho claro, ai tipo se a condição cor for igual a vermelho, quero simular que passa por todas as cores até chegar vermelho ou seja é uma roleta, que basicamente  mostra a imagem do verde escuro > mostra a imagem do verde claro, espera 1 segundo,  ativa  mostra imagem do laranja escuro > mostra imagem do laranja claro etc... até chegar ao vermelho
Comment: Posso usar Jquery, nao tem problema.
Comment: @Gonçalo, adicionei um link na resposta. ;)
Comment: Amigo diga-me so uma coisa, isto funciona no mesmo id de img?
Comment: Sim @Gonçalo, você pode fazer direto `document.getElementById(id).setAttribute('src', 'caminho/da/imagem.jpg');`
Comment: Já consegui Obrigado!
Answer: Você pode utilizar o setTimeout para gerar o delay desejado.
function iniciarSlideImagens() {

    var exibirImagens = function(current) {
        var arrImgsAmarelas = [ 'amarelo0.png', 'amarelo1.png' ];
        var arrImgsLaranjas = [ 'laranja0.png', 'laranja1.png' ];

        document.getElementById("imagem").src = "cores-roleta/" + arrImgsAmarelas[current];
        document.getElementById("imagem1").src = "cores-roleta/" + arrImgsLaranjas[current];

        if (++current >= arrImgsAmarelas.length) {
            current = 0;
        }

        setTimeout(function() { exibirImagens(current); }, 5000);
    };

    exibirImagens(0);

}

iniciarSlideImagens();

Comment: Boa Tarde, isso no caso altera apenas um id de um img, eu queria que alterasse varios ids de varios imgs.
Comment: @Gonçalo Editei a resposta.
Comment: Eu coloquei o código da seguinte forma: http://pastebin.com/TLLAT0JE E só me aparece apenas a imagem da img.
Comment: Como assim a imagem da img? Faltou você alterar o seletor para a imagem laranja, que deveria ser `imagem1` e você manteve `imagem2`.
Comment: Bom Dia, peço desculpa mas sou mesmo iniciante na área, pode-me indicar o que é seletor?. Obrigado.
Comment: O problema era na linha `document.getElementById("imagem2")` que deveria ser `imagem1`. Editei o código da resposta para fechar com o seu exemplo.
Comment: Amigo, o que está a acontecer é isto:  https://www.youtube.com/watch?v=mYC0TPUldPc Eu queria que primeira ligasse o amarelo(amarelo1.png) passada 5 segundos desligava o amarelo(amarelo0.png) e ligasse sem intervalo de tempo o laranja(laranja1.png) e etc...
Comment: Opa @Gonçalo, depois de ver o que você quer, essa solução do Oeslei te cabe bem, fiz uns ajustes nela. https://jsfiddle.net/nxvh7fru/


Android Tablet Application Development Query

Question: I am an ANDROID app developer,
i just need to know, that what are the conditions and things ,to create app for android tablets.
Is there any registration fees apart from the $25, where should i register and how to develop, is it different from android mobile app development.
Plz suggest.
Regards
Comment: NO its not that much different from android mobile app. Just some screen size/resolution and/or any extra h\w functionality can be differ. You can get the emulator to develop tab app.
Comment: so i just change my emulator screen resolution to 1024 by 768 and i am done with Table app ???
Comment: Yes, if you do not care your app would look crappy on tablets.
Answer: No there are no significant changes as of yet. However, the 3.0 SDK will add several new features we haven't used before as well as hardware acceleration. sweet! :) good luck!
Comment: Thanks,one more thing, where should i upload tablet app?At the same place, where we upload android mobile app? how it gonna be different from from mobile app? thanks again
Comment: I actually don't know for sure, but I guess it all comes down to how you tag and specify your app. If you are making a "tablet only-app" i think you should make it very clear to the potential downloaders. Oh, and the Market is the same for both tablets and phones... :)


drupal_mail() new line \n not working

Question: I'm trying to insert a new line in message body using \n but it's not working.
Tried already with \r\n and it doesn't work also.
Any help?
Tks.
Answer: Could be a couple things, without seeing any of your code it's difficult to help you.
Try:

Making sure you're using double quotes (") instead of single quotes (') around the new line characters. (This is because PHP does not interpolate strings defined by single quotes).
Setting the Content-Type to text/plain in the mail headers. (If you need HTML in your email, use
 for new lines).

Also, you should always use \r\n with emails so the new line is recognized across all platforms.
Answer: Are using double quotes? They are necessary for the special characters to be interpreted correctly.

drupal_mail() new line \n not working


Why is transferring large local files in PowerShell so slow for me

Question: I am currently using PowerShell's Copy-Item commandlet to create a copy of a 500GB file and transferring it to another local hard drive on the computer. Doing it this way is really slow: a couple hours for it to finish. When I simply right-click the file, select copy, and paste, the transfer takes about an hour. Is there another PowerShell cmdlet to use to get faster transfer time?
EDIT:
Powershell commandlet iam currently using Copy-Item -Path G:\Backups  -Destination I:\Backups  -Force -Recurse
Comment: Please share the actual commands that you are running. Are you making a copy of the file and then moving that copy, or just using one instance of the Copy-Item cmdlet to create your copy?
Answer:
Is there another PowerShell cmdlet to use to get faster transfer time?

It's slow because it is using buffered I/O. If you want performance parity use a native Windows command such as XCOPY or RoboCopy and use unbuffered I/O.
Comment: yep robocopy helped alot in transfer time thanks
Comment: Any ideas why the native windows command is not the default in PowerShell on a Windows system?


How to get simple text from HTML page with goquery?

Question: I am new to Go. I am using goquery to extract data from an HTML page.
But the problem is the data I am looking for is not bounded by any HTML tag. It is simple text after a
 tag. How can I extract it?
Edit : Here is HTML code.

NamePriyaka

SurnamePatil

Adress
India,Kolhapur

Hobbies
Playing

Eduction
12th

School
New Highschool

From this I want "Priyanka" and "12th".
Comment: Can you give an example of how that HTML looks?
Comment: Maybe you just need to use `regexp` to extract your data?
Comment: When it is not to be taken (Contraindications):   Contraindicated in patients with severe liver impairment, and hypersensitivity.
Comment: I would edit your questions with that comment @Shirin
Comment: Edited. Have a look @Not_a_Golfer
Answer: The following is what you want:
doc.Find(".container").Find("[align=\"justify\"]").Each(func(_ int, s *goquery.Selection) {
    prefix := s.Find("b").Text()
    result := strings.TrimPrefix(s.Text(), prefix)
    println(result)
})

import strings in front of your code. If you need complete code example, check here.
Answer: Try query for  and get its siblings
http://godoc.org/github.com/PuerkitoBio/goquery#Selection.Siblings


How do I use this module which depends from a module that is not available for the core version I am using?

Question: I'm trying to install the Juicebox HTML5 Responsive Image Galleries module to the Drupal 8 site but the system doesn't allow me to do so because the Libraries API module is missing. The modules page shows the following.

Is it possible to use the Juicebox HTML5 Responsive Image Galleries module even if there is no Drupal 8 version for the Libraries API module? Could it work with the 7.x-2.3 version?
The project page for the Libraries API module shows the following message:

This module is currently being ported to Drupal 8, but is not usable yet. Help us by following this issue.

Does it mean I can't use this API module for the Drupal 8?
Comment: You cannot install Drupal 7 modules in a Drupal 8 site.
Answer: Welcome to Drupal Answers.
You don't need additional module for Libraries on Drupal 8, just create libraries folder in root of a Drupal project and put all libraries you need there.
In this case download juicebox library unarchive it, put the unarchived folder in libraries folder you created and rename it to juicebox, so your library should be in /libraries/juicebox.
And that's it, you can enable your module.
Comment: The OP is using a module that declares the _Libraries API_ module as dependency.
Answer: The Juicebox HTML5 Responsive Image Galleries module lists the Libraries API module as dependency in juicebox.info.yml. This means that Drupal will not let you install the Juicebox HTML5 Responsive Image Galleries module if it doesn't find the Libraries API module in one of the directories where Drupal looks for modules, or if the Libraries API module is not first installed. (In the first case, Drupal will install both the modules when you install the Juicebox HTML5 Responsive Image Galleries module.)
There is a Drupal 8 development snapshot for the Libraries API module. You can find it clicking on View all releases in the project page for the Libraries API module. The fact is not directly shown in the project page probably means the module is not ready to be used in Drupal 8.
There is also an issue opened for Drupal core (Libraries API in core) which makes me think they aren't releasing any stable release for Drupal 8, waiting for the module to be accepted to be included as core module.
What you can do right now is installing the 8.x-3.x version of the Libraries API, knowing that the last update has been done on March 15, 2017, and that you could have some problems using it. I would rather test it in a test site where you install all the modules you are using in the production server, and see which problems that causes.
The alternative is using a module with the same feature the Juicebox HTML5 Responsive Image Galleries module has, or a module that has the same features you are using from the Juicebox HTML5 Responsive Image Galleries module.
Using a Drupal 7 version of a module with Drupal 8 doesn't work as, to start, Drupal 8 requires modules have a .info.yml file, while Drupal 7 requires a .info file containing information in a totally different format.


Como deletar todos os duplicados, exceto um?

Question: Tenho uma tabela que possui registros duplicados. Eles não deveriam estar duplicados.
Alguns registros duplicaram duas, cinco e até trinta vezes por acidente.
Preciso remover esses registros duplicados, porém preciso deixar um. Então, por exemplo, se eu tenho um valor repetindo 30 vezes, preciso deletar 29.
Meu cenário é mais ou menos esse:
SELECT * FROM creditos WHERE status = 0

O resultado está assim:

id | usuario_id | status

1  |   1         | 0
2  |   2         | 0
3  |   5         | 0
4  |   5         | 0
5  |   5         | 0
6  |   15        | 0
7  |   15        | 0
8  |   15        | 0
9  |   15        | 0
10 |   17        | 0

Mas preciso que fique assim:

id |  usuario_id | status
1  |   1         | 0
2  |   2         | 0
5  |   5         | 0
9  |   15        | 0
10 |   17        | 0

Nota: Só quero deletar os duplicados se o status for 0, porém quero deixar um.
Como fazer uma query que delete os duplicados, porém deixando sempre um registro?
Comment: Usa o `having`.
Comment: Com o `HAVING` vai deletar tudo, não?
Comment: Qual a versão do MySQL?
Answer: Poderia obter o menor id agrupando pelo usuário e remover todos os demais.
Ficaria algo semelhante a isso:
delete from creditos where status = 0 and id not in
( SELECT * FROM
    (select min(id) from creditos group by usuario_id) AS temp_tab
);

Note que o status = 0 está no DELETE e não na sub consulta. Caso queira que o id retornado seja com o status = 0, adicione esse WHERE também na sub consulta.
Você também pode ver essa e demais formas nestas respostas:

How can I remove duplicate rows?
Delete all but one duplicate record
Comment: Acho que você teria que trocar o min() por max() e ficaria melhor se fosse com not exists no lugar de not in.
Comment: @MarconcilioSouza Creio que o `min()` ou o `max()` vai de acordo com a necessidade. A única diferença seria se iria permanecer o primeiro registro ou o último. Sobre o `exists()` e o `not in()` geraria diferença se o retorno fosse null ou uma questão de tempo. Porém, não me parece que seja o caso da pergunta.
Answer: Uma forma é adicionar um índice com a coluna que você deseja manter como única adicionando a cláusula IGNORE que irá suprimir possíveis erros e avisos e apagar as linhas que não obedecerem o índice criado:
ALTER IGNORE TABLE creditos
ADD UNIQUE INDEX idx_creditos (usuario_id, status);

ALTER TABLE
...
IGNORE is a MySQL extension to standard SQL. It controls how ALTER TABLE works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. If IGNORE is specified, only the first row is used of rows with duplicates on a unique key, The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.
...

Ou em tradução livre:

...
IGNORE é uma extensão do MySQL a SQL padrão. Ela controla como o ALTER TABLE trabalha caso existam duplicadas em chaves únicas na nova tabela ou se algum aviso acontece quando o modo estrito está ativado. Se o IGNOREnão for especificado, a cópia é abortada e desfeita se erros de chave duplicada ocorrerem. Se IGNORE for especificado, apenas a primeira linha é usada das linhas com chaves duplicadas em chaves únicas. As outras linhas com conflito serão apagadas. Valores incorretos são "truncados" para o valor aceitável mais próximo.
...

Outro método é utilizar o DELETE para apagar as linhas duplicadas.
Primeiramente você tem que vincular a tabela com ela mesma de acordo com a coluna desejada. Você pode fazer isso diretamente na cláusula FROM ou com um JOIN:
FROM creditos c1,
     creditos c2
...
WHERE c1.usuario_id = c2.usuario_id
  AND c1.status = c2.status

ou
...
FROM creditos c1
     INNER JOIN c2 ON c1.usuario_id = c2.usuario_id
                  AND c1.status = c2.status

Logo após isso indique qual vai ser o critério para apagar o registro, como por exemplo, caso queira selecionar e apagar os registros com maior id. Adicione a cláusula AND (considerando o primeiro exemplo):
...
AND c1.id > c2.id

Para o segundo exemplo:
...
WHERE c1.id > c2.id

Caso queira selecionar e apagar os de menor id, respectivamente teríamos:
...
AND c1.id < c2.id

e
...
WHERE c1.id < c2.id

Agora adicionaremos o atributo que irá filtrar o registro, de acordo com o seu exemplo:
...
AND c.status = 0

Aplicando os passos descritos acima
Se você quiser selecionar e apagar o registro de menor id:
DELETE c1
  FROM creditos c1,
       creditos c2
 WHERE c1.id > c2.id
   AND c1.usuario_id = c2.usuario_id
   AND c1.status = c2.status
   AND c1.status = 0;

Resultando em (veja funcionando no DB Fiddle):
| id  | usuario_id | status |
| --- | ---------- | ------ |
| 1   | 1          | 0      |
| 2   | 2          | 0      |
| 3   | 5          | 0      |
| 6   | 15         | 0      |
| 10  | 17         | 0      |

Ou usando INNER JOIN:
DELETE c1
  FROM creditos c1
 INNER JOIN creditos c2 ON c1.usuario_id = c2.usuario_id
                       AND c1.status = c2.status
 WHERE c1.id > c2.id
   AND c1.status = 0;

Resultando em (veja funcionando no DB Fiddle):
| id  | usuario_id | status |
| --- | ---------- | ------ |
| 1   | 1          | 0      |
| 2   | 2          | 0      |
| 3   | 5          | 0      |
| 6   | 15         | 0      |
| 10  | 17         | 0      |

Se você quiser selecionar e apagar o registro de maior id:
DELETE c1
  FROM creditos c1,
       creditos c2
 WHERE c1.id < c2.id
   AND c1.usuario_id = c2.usuario_id
   AND c1.status = c2.status
   AND c1.status = 0;

Resultando em (veja funcionando no DB Fiddle):
| id  | usuario_id | status |
| --- | ---------- | ------ |
| 1   | 1          | 0      |
| 2   | 2          | 0      |
| 5   | 5          | 0      |
| 9   | 15         | 0      |
| 10  | 17         | 0      |

Ou usando INNER JOIN:
DELETE c1
  FROM creditos c1
 INNER JOIN creditos c2 ON c1.usuario_id = c2.usuario_id
                       AND c1.status = c2.status
 WHERE c1.id < c2.id
   AND c1.status = 0;

Resultando em (veja funcionando no DB Fiddle):
| id  | usuario_id | status |
| --- | ---------- | ------ |
| 1   | 1          | 0      |
| 2   | 2          | 0      |
| 5   | 5          | 0      |
| 9   | 15         | 0      |
| 10  | 17         | 0      |

Observação: Para testar os dados antes de apagar, você pode utilizar SELECT c1.* ao invés de DELETE c1 nos exemplos citados acima.

Referências:

Delete all Duplicate Rows except for One in MySQL?
Remove duplicate rows in MySQL
Comment: `where c1.status = c2.status`.. daí posso colocar `and c1.status = 0`?
Comment: Se você quiser deletar só as de código 0 sim, mas vc tem que colocar o `and c2.status = 0` também pra poder ligar os registros
Answer: Em um modo mais simples e pratico:
 Espero ajuda-lo
with cte as
(
   select usuario_id ,
          row_number ()  over ( partition  by usuario_id order  by usuario_id )  as r
    from creditos where status = 0

 )
delete cte where r >  1 ;

Comment: Só faltou comunicar que isso só funciona pra versões mais recentes do `MySQL`
Answer: No MySQL 8.0 existe a possibilidade de usar RANK()
SELECT
    id, usuario_id, status
FROM (
  SELECT
    id, usuario_id, status,
    RANK() OVER (PARTITION BY usuario_id ORDER BY id DESC) AS intRow
  FROM
    Table1
  WHERE
    status = 0
) T
WHERE
    intRow = 1

https://www.db-fiddle.com/f/7V6HBDsCmd4m9uPiz9cnWY/0
Para deletar os registros com ID repetido você poderia usar um código como esse:
DELETE FROM Table1
WHERE
    id IN (
      SELECT
          id
      FROM (
            SELECT id, RANK() OVER (PARTITION BY usuario_id ORDER BY id DESC)  AS intRow
            FROM Table1 WHERE status = 0
      ) T WHERE intRow > 1
    );

https://www.db-fiddle.com/f/7V6HBDsCmd4m9uPiz9cnWY/2
Answer: Não questionando o merito tecnico das soluções propostas, mas quando eu me defronto com isto simplesmente faço algo assim:
        SELECT  DISTINCT
                COLUNA1
               ,COLUNA2
               ,COLUNA3
        INTO #TEMP
        FROM TABELA
        WHERE COLUNA = 'XPTO'

        DELETE FROM TABELA
        WHERE COLUNA = 'XPTO'

        INSERT  TABELA (
                        COLUNA1
                       ,COLUNA2
                       ,COLUNA3
                       )
        SELECT  COLUNA1
               ,COLUNA2
               ,COLUNA3
        FROM #TEMP

Não é uma questão de conhecimento ou preguiça de pensar, é apenas uma questão de resolver logo uma situação especifica e acabar com o problema
Comment: Aí você vai fazer um por um?


Compute the higher derivatives of $B(h,h)$

Question: I'm trying compute the higher derivatives of $B(h,h)$, but I'm stuck when I tried compute the second derivative of this question. I would like to know if my attempt is correct and how can I found the second derivative of $B(h,h)$

$\textbf{Problem:}$ Let $f: \mathbb{R}^n \longrightarrow \mathbb{R}^m$ defined by $f(x) := B(x,x)$, where $B: \mathbb{R}^n \times \mathbb{R}^n \longrightarrow \mathbb{R}^m$ is a bilinear form. Compute the higher derivatives of $f$.
$\textbf{My attempt:}$
I know that $B$ is differentiable and $DB(a,b) \cdot (h,k) = B(a,k) + B(h,b)$ for every $(a,b), (h,k) \in \mathbb{R}^n \times \mathbb{R}^n$.
Defining $C: \mathbb{R}^n \longrightarrow \mathbb{R}^n \times \mathbb{R}^n$ by $C(h) := (h,h)$ e noting that $C$ is linear, I know that $DC(h) \cdot k = C(k)$ for every $h, k \in \mathbb{R}^n$.
By the Chain of Rule,
$Df(x) \cdot h = D \left( B \circ C \right)(x) = DB(C(x)) \circ DC(x) \cdot h = DB((x,x)) \ \circ \ C(h)$
$ = DB((x,x)) \cdot (h,h) = B(x,h) + B(h,x) = 2 B(x,h)$

for every $h, k \in \mathbb{R}^n$.

Using the definition of differentiability to compute $D^2f(h)$, I found
$Df(x+h) \cdot h = Df(x) \cdot h + D^2f(x) \cdot (h,h) + r(h)$
$2 B(x+h,h) = 2 B(x,h) + D^2f(x) \cdot (h,h) + r(h)$
$2 B(x,h) + 2 B(h,h) = 2 B(x,h) + D^2f(x) \cdot (h,h) + r(h)$
$2 B(h,h) = D^2f(x) \cdot (h,h) + r(h)$
By the continuity of $B$ and $D^2f(x)$, I have that $\lim_{h \rightarrow 0} r(h) = 0$, which implies that $\lim_{h \rightarrow 0} \frac{r(h)}{||h||} = 0$, then $Df(x)$ is differentiable, but this don't give me the second derivative of $f$.

How can I found the second derivative of $f$? Is it easy find the $n$-th order derivative of $f$ for $n \geq 3$ once I have the second derivative of $f$? Thanks in advance!
Answer: I first have a comment: based on what you wrote, you're not only supposing that $B$ is bilinear, but also symmetric.
Now, you correctly proved that $Df(x).h = 2 B(x,h)$. Which implies that $Df$ is a linear application defined from $\mathbb R^n$ into $\mathcal L(\mathbb R^n, \mathbb R^m)$.
You also know (or you can prove) that the derivative of a linear map $L$ is the constant linear map $L$. Therefore $f$ second derivative is constant and equal to $2B$. As the derivative of a constant map is zero, the higher than $2$ derivatives of $f$ are all equal to zero.
Comment: I thought that second derivative of $f$ is a constant linear map because $Df(x)$ is a linear map, but I found difficult to argue this. How can I argue this? Is it $D^2f(x) \cdot (h,h) = 2B(x,h)$?
Comment: You have $Df(x+k).h=2B(x+k,h)=2B(x,h)+2B(k,h)=Df(x).h+2B(k,h)$. Hence $D^2f(x).(h,h) = 2B(h,h)$ which is indeed independent from $x$.
Comment: I understood, thanks a lot!


How to stabilize model performance?

Question: I am performing a regression classification to predict genes that are likely to cause disease. I have 600 rows of training genes by 8 features. Although only 50 genes have a score >0.9 (on a scale of 0 to 1, where 1 is definitely causing disease and 0 is a gene not causing the disease)  and unfortunately cannot increase this, whilst I also have ~400 genes <0.1
I benchmark a few models using nested cross-validation and Bayesian hyperparameter tuning (models: gradient boosting, extreme gradient boosting, random forest, support vector machine, and k-nearest neighbors).
I assess model performance with all the metrics scikit-learn has to offer for regression classification (MSE, MAE, max error, r2, etc.). However when I re-run the same code I get small flucuations in these measures (e.g. r2 changes from 0.70 to 0.71.
Differences in performance have only been +/- 0.01 on my re-runs, but this concerns me as I thought I've done everything to make sure the performance is stable.
Is there anything I can do further check/ensure model performance stability? I thought about removing some of the genes that have <0.1 score to reduce the imbalance between them and the few genes that score >0.9 but I'm not sure if this is good practice? Also wouldn't go for synthetically increasing high scored genes as I'm not sure that's trustworthy either.
I have also:

Set the random_state seed globally (to 0)
I select the 8 features using the Boruta algorithm and check model performance further with shap
Checked that the imputation on the data before machine learning also outputs a stable dataset (so the data going into the models is the same every time). I use missforest random forest imputation for this.
For the tree-based models I don't scale or normalize data but for the other non-tree-based I do scaling.

Gradient boosting is my top model so in theory if its performance was stable I'd go for using that model, and so as an example the parameter tuning I do looks like:
seed=0
gbr = GradientBoostingRegressor(random_state=seed)
gbr_params = {
    'learning_rate': (0.01, 0.5),
    'max_depth': (1, 4),
    "max_features":["log2","sqrt", "auto"],
    "criterion": ["friedman_mse", "mse", "mae"],
    'n_estimators': (10, 50)
    }

inner_cv = KFold(n_splits=5, shuffle=True, random_state=seed)
outer_cv = KFold(n_splits=5, shuffle=True, random_state=seed)

I also use sklearn's train_test_split() for which I also set the same seed of 0.
Answer: Imho there is a global flaw, as you have not integrated for example imputing, e.g. with knn, and scaling within a pipeline. This may lead to overfitting, as the train data may see the test data e.g. from scaling, when doing it manually. From your code, I can not judge, what you are doing in detail. But you should base your predictions on a GridEstimator pipeline with SMOTE for inbalacing, scaling, and KNN:
e.g. something like this:
#' split
X_train, X_test, y_train, y_test = train_test_split(X1, y, random_state = 42)

#Pipeline classifiers
classifiers = [RandomForestClassifier(), DecisionTreeClassifier()]

#' auto and manual selection'
steps_auto = [
    ('Impute KNN', KNNImputer(n_neighbors=3)),
    ('SMOTE', SMOTE()),
    ('RFTrees', classifiers[0])
]

#' to add Feature Selection, if you want
steps_manual = [
    ('Impute KNN', KNNImputer(n_neighbors=3)),
    ('SMOTE', SMOTE()),
    ('Feature Selection', SelectFromModel(estimator=ExtraTreesClassifier())),
    ('RFTrees', classifiers[0])
]

pipeline_auto = Pipeline(steps_auto)
pipeline_manual = Pipeline(steps_manual)
#'choose params for grid/randomsearch'

params = {
          #'Trees__n_estimators': [100],
          'RFTrees__criterion': ["entropy"], #'entropy better'
          'RFTrees__max_depth': [3, 4, 5, 6, 7, 10, 15],
          'RFTrees__min_samples_split': [2, 3, 4, 10],
          'RFTrees__min_samples_leaf': [2, 3, 4, 10],
         }

grid_auto = GridSearchCV(pipeline_manual, param_grid=params, cv=10, n_jobs=-1, random_state = 42)
#' or

grid_manual = GridSearchCV(...)

I have not double checked the code, it is a template of myself, feel free to use it for your test and estimator or adapt it. And you need to add scaling, but pipelining makes everything relatively save in terms of subfolds and their values and sizes etc., in addition grid search really searches for the best solution...
If you really want to only care about accuracy you should check permutation importance of features to get a hint, which features you really need. If you want to have a look at the features individual contribution and how the data points affect your model: use the

shap library

After all that your model should be relatively stable, do not forget to tell your SMOTE which is the minority class

How to stabilize model performance?


change domain proxy_pass to ip

Question: I used reverse proxy but seeing the nginx log it changes the address to ip and it doesn't work because the destination server is vhost and it only works with domains.
location  = /video {
    resolver 184.108.40.206;
    if ( $arg_net != "" ) {
        proxy_pass https://$arg_net.serverA.com;
    }
    proxy_redirect off;
  }

I see in the nginx log
... upstream: "https://[2a02:2518:4:3875::d]:443/video?net=...

How can I use it only with the domain??
Answer: That's why proxy_set_header exists, and you need
proxy_pass https://$arg_net.serverA.com;
proxy_set_header Host "$arg_net.serverA.com";

https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/#passing-request-headers

change domain proxy_pass to ip


Show where f(x,y)=min(|x|,|y|) is differentiable

Question: Is f(x,y)=min(|x|,|y|) differentiable at point (0,0) and find the partial derivatives at the origin if they exist.
Now
$f(x,y)$=\begin{cases}
                 |x|, & |x|\leq |y| \\
     \
                 |y|, & |y|<|x|
                \end{cases}
$\frac{\partial{f(x,y)}}{\partial{x}}= \begin{cases}
                 \frac{x}{|x|}, & |x|\leq |y| \\
     \
                 0, & otherwise
                \end{cases}$
Answer: No, the function is not differentiable at the origin. For example look at the line passing through the origin $y = x$. Here we have $f(x,x) = |x|$ which is not differentiable at $0$.
Note that if you look at the line $x = 0$ then $f(0,y) = 0$ and likewise with the line $y = 0$, so the partial derivatives in the directions $(1,0)$ and $(0,1)$ are 0.
However, given any other line through the origin we get $f(ax,bx) = min(a,b)|x|$ is not differentiable at $0$, so the directional derivative does not exist.
Comment: So don't you think you should replace your last "partial derivative" by "directionnal derivative" ? Becauses as you mentionned, both partial derivatives exist here.
Comment: The directionnal derivatives may exists in every direction while the function being not differentiable. I do not understand your last sentence.
Comment: The linear restrictions of the function are differentiable for this function if and only if the linear restrictions are in the coordinate directions.
Comment: Great point! Updated.


How to detect inflection points without function expression in a live time series scenario?

Question: Most of the learnings and examples out there talks about finding inflection point given there is a function expression. What happens when I do-not know the function expression? The movement of the graph is not defined by any formula and the graph is live in nature .

How to calculate the inflection points, positive, negative slopes from the graph itself in a continuous manner in time ?
Comment: Could you maybe give a plot of some example data? You could always fit a cubic polynomial to successive intervals of time with enough data to make it reasonable (this is called cubic splines), and then compute the inflection points in the cubics.
Comment: @AdrianKeister I have added a picture to get a better view, this is the graph and the incoming values is not within my control, all matters to me are the inflection points, therefore the question is how to detect them?
Comment: Have a look at scipy methods for peak finding: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html#scipy.signal.find_peaks
Answer: OK, VERY IMPORTANT: what you've circled are most definitely NOT inflection points. You have circled local minima. There are many algorithms for finding those that are very efficient. One of the easiest things you could do, I think, is simply multiply all the $y$ values by $-1$ and then use a peak-finding routine. Peak-finders are very common and not difficult to find. The trick with peak-finders is to choose the window size. If you choose it too large, your algorithms gets "ham-fisted" and won't detect peaks in a smaller region very well. On the other hand, your data oscillates enough to where setting the window size too small will find far too many peaks. Another thing you could try is first filtering your data before running it through the peak-finder. I find a median filter works well if you have a lot of outliers. Your example data doesn't look like it has too many outliers, so maybe just a regular low-pass filter would do the trick. So that's my recommendation: use a low-pass filter (plot the filtered on top of the unfiltered to make sure your cutoff frequency is set reasonably) then use the peak-finder on $-y.$
Comment: Haven't used it, but definitely try it out, particularly if it's based on numpy (it seems hard to get documentation on python-peakutil!). Make sure to plot the results, and see if you like them.
Comment: Thanks a lot for the direction , i am very new to the math application world, would you recommend python-peakutil as a peak finder ?


Como fazer loop para enviar meus emails?

Question: Estou tentando fazer o código pegar os emails que vou por em uma lista .txt ou em um form (enquanto não monto o banco de dados) e fazer um loop para enviar todos os emails. Acontece que estou recebendo esta mensagem de erro e não sei como solucionar o problema.
<?PHP

require_once('class.phpmailer.php');

$nm = $_GET['nome'];
$sb = $_GET['sobrenome'];

$address = "firstname.lastname@example.com";
$address = "firstname.lastname@example.com";

for($loop=0; $loop<4; $loop++){

  $mail = new PHPMailer();
  $body = file_get_contents('a.html');

  $mail->AddReplyTo("email@example.com","EREA SSA");
  $mail->SetFrom('firstname.lastname@example.com', 'EREA SSA');

  // Nome e Sobrenome pegos através do GET "site.com/email.php?nome=André&sobrenome=Leal"
  $mail->AddAddress($address[$loop], utf8_decode("$nm[$loop] $sb[$loop]"));
  $mail->Subject = "Teste !";
  $mail->MsgHTML($body);

  //$mail->AddAttachment(""); // Arquivos para anexo

  if(!$mail->Send()) {
    echo "Erro: " . $mail->ErrorInfo . "
";
  } else {
    echo "Mensagem enviada !";
  }
  $mail->clearAllRecipients(); // Limpa o campo de para quem o email será enviado e o nome

}

?>

Answer: Bom, a solução já foi encontrada, logo a baixo deixo a solução do problema para quem quiser usar para estudar.
<?PHP

require_once('class.phpmailer.php');

$nm = $_GET['nome'];
$sb = $_GET['sobrenome'];

$address[] = "firstname.lastname@example.com";
$address[] = "email@example.com";
$address[] = "firstname.lastname@example.com";
$address[] = "firstname.lastname@example.com";

foreach($address as $addr){

  $mail = new PHPMailer();
  $body = file_get_contents('a.html');

  $mail->AddReplyTo("email@example.com","Opa Epa");
  $mail->SetFrom('firstname.lastname@example.com', 'Opa Epa');

  $mail->AddAddress($addr, utf8_decode("$nm[$loop] $sb[$loop]"));
  $mail->Subject = "Teste !";
  $mail->MsgHTML($body);

  //$mail->AddAttachment(""); // Arquivos para anexo

  if(!$mail->Send()) {
    echo "Erro: " . $mail->ErrorInfo . "
";
  } else {
    echo "Mensagem enviada !
";
  }
  $mail->clearAllRecipients(); // Limpa o campo de para quem o email será enviado e o nome

}

?>


How to find position vector of circle?

Question: so I have a question on solving the following:
"A particle moves around the circle $x^2+y^2=25$ at constant speed, making one revolution in 2s. Find its acceleration?"
In the solution it says, that it's easy to see that the position vector is given by $$\textbf{r}=5cos(\omega t)\textbf{i}+5sin(\omega t)\textbf{j}$$
but unfortunately for me is not so easy to see, why can I say that this is the vector position? Does the formula $\textbf{r}=acos(\omega t)\textbf{i}+bsin(\omega t)\textbf{j}$ only hold for circles (does this formula has a name?)?
and the last thing I want to ask is with one revolution, do they mean that the particle has travelled one cicle?
If you know the answer and would like to share it, it would be very much appreciated
Thanks in advance!
Comment: This link: https://www.mathsisfun.com/geometry/unit-circle.html may help you understand the equation. And yes, one revolution is one circle
Answer: Hint: what is the paramtric form of a point on the circle?
This corresponds to the position of the rider at any time t.
For your second question, yes, this means the particle has travelled one full circle, from starting point to starting point.
Comment: Thank you so much @Ishraaq Parvez!

How to find position vector of circle?


Django cache doesn't store all cached elements

Question: I'm used DB and filebased cache with my django 1.4.1 project.
I have more than 100 000 elements that should be cached, they are caching for 48 hours.
But elements in cache are disapearing too early and cache coverage is about 10%.
For example, main page should be generated only one time in 48 hours, but It get's from cache only 30% of hits, other 70% of requests doesn't find cached version and regenerates main page.
cache_time = 60*60*24*2
body_html = cache.get('index')
if not body_html:
    body_html = generate_page_html_content()
    cache.set('index', body_html, cache_time)
#do something with body_html

For db cache SELECT count(*) FROM cache; returned 224 cached items but there should be much more of them. What can be wrong?
Answer: Here is the solution: https://docs.djangoproject.com/en/dev/topics/cache/#cache-arguments
I added MAX_ENTRIES option and set limit, that is suitable for me.


Usar classe Auth em arquivo de configuração no Laravel

Question: Estou usando o barryvdh/laravel-elfinder. Este gera o arquivo de configuração /config/elfinder.php. Dentro deste arquivo, informo o caminho para upload de arquivos do ElFinder.
Preciso que cada usuário tenha a sua pasta de uploads. Pensei em criar uma variável $dir de acordo com o id do usuário logado mas não consigo usar a classe Auth dentro do arquivo /config/elfinder.php.
Tem jeito de pegar o usuário logado de outra forma?
O arquivo está assim:
<?php

$dir = 'arquivos';
return array('dir' => [$dir] );

Quero algo assim:
<php

$dir = 'arquivos/'.Auth::id();
return array('dir' => [$dir] );

Já tentei assim:
<?php

use Auth;
$id=Auth::id();

$dir = 'arquivos/'.$id;
return array('dir' => [$dir] );

E retorna este erro:

Warning: The use statement with non-compound name 'Auth' has no effect in /var/www/html/dna/config/elfinder.php on line 3

Fatal error: Class 'Auth' not found in /var/www/html/dna/config/elfinder.php on line 5

Comment: Não consegue colocar no topo da página `use Auth;`
Comment: Não funciona, já tentei
Comment: Vai dar pau mesmo. Essa classe provavelmente nem passou para o processamento de alias que o Laravel faz internamente. Provalvemente, é a ordem que o script tá sendo executado internamente.
Comment: Veja se funciona sessão. Ao logar coloca o ID na sessão e pega no arquivo do elfinder.php.
Comment: @Gumball não vai funcionar também. Tem um problema muito mais sério do que isso no Laravel 5. Os middlewares e o autoload afetam o carregamento dos dados do Auth também.
Comment: Se tratando dos arquivos da pasta `config` é verdade. É preciso ter uma outra saída.
Answer: Esse erro costuma acontecer porque o arquivo de configuração é carregado antes de acontecer o processamento interno que o Laravel faz para a classe Auth (que é um alias).
Além desse problema, dependendo dos locais da aplicação onde você pode querer tentar acessar o valor de Auth::user, o retorno pode vir null independente de estar logado ou não. Isso ocorre porque os dados do Auth só são acessíveis depois do carregamento desses middlewares abaixo:
    \Tmt\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,

Eles são responsáveis pela sessão, cookies e afins.
Solução
Você pode considerar a utilização da função config para poder definir de acordo com o usuário logado dentro de um Middleware. Pois usando um middleware, está trabalhando com dados vindos da sessão, já que os mesmos já foram carregados pelos middlewares anteriores.
Por exemplo
class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // Restante do código

        config(['elfinder.dir' => ['arquivos/' . auth()->user()->id]])

        return $next($request);
    }
}

É bom observar que a ideia de usar o config é para trabalhar com dados imutáveis.
Talvez ainda fosse interessante observar se a biblioteca que você está usando não existe um método para você poder definir qual diretório vai trabalhar.
Comment: Exatamente. É preciso reescrever a variável no ato do login por meio de uma Middleware.Tipo: `Route::group(['prefix' => 'auth', 'middleware' => ['auth', 'path-upload']], function(){  });`. Daí na Middleware `path-upload` reescreve.
Comment: @Gumball isso, se ela precisar ela pode definir um `middleware` global, ou então botar ele dentro do grupo `web`.


Duvida de implantação arquitetura com elasticsearch?

Question: Ola,
é normal usar o elasticsearch como backend direto em uma aplicação para web.
Referente a segurança?
FrontEnd (js) -> Backend (elasticsearch)
ou
FrontEnd (js) -> seu backend -> service (elasticsearch)
A minha grande preocupação seria na segurança de acesso ao elasticsearch.
Alguem já usa elasticsearch em produção desta forma...
Grato
Comment: Não é normal usar o ES como "back-end" até por que ele é um indexador de documentos e não um banco de dados.
Answer: Depende muito...
Eu não recomendaria utilizar o Elasticsearch como banco de dados primário, até por que ele é um documento. Uma vez que os dados estão lá, os dados são transformados e armazenados no cluster do elasticsearch para análise. Mas se você está construindo sistemas completamente novos, então você tem TOTAL liberdade.
Eu ficaria com a segunda opção: Front-end -> Back-end -> DB -> ES
O ideal é você possuir o seu modelo de negócio funcionando normalmente em um banco de dados SQL ou noSQL (você escolhe) e caso você precise analisar ou consultar dados utilizar o Elasticsearch para usufruir de sua facilidade e alto desempenho.
Comment: Show, Obrigado, eu já tenho uma arquitetura funcional e meu db principal é outro, seria apenas essa arquitetura para consulta msm, mais a minha preocupação é a segurança de usar apenas elastic, sobre acesso externo ao elastic.... Muito obrigado pela resposta :)
Comment: Bacana @SidicleiF.Almeida ! Fico feliz em poder ajuda-lo.
Answer: ElasticSearch é um motor de busca real time baseado em lucene, naturalmente distribuído, escalável e servidor rest. Ele basicamente usa o lucene para fazer indexação dos dados e torna isso escalável através de clusterização e replicação dos índices.
ElasticSearch deve ser usado apenas para busca pois não possui forte integridade referencial e em algum momento os índices podem ser corrompidos, principal quando você começa a escalar os nós.
O ideal é você usar a seguinte estrutura: Front End JS/ Back End JS/ Acesso a dados(Algum banco relacional ou NOSQL e indexar o que é relevante para pesquisa no elasticsearch.
O uso do elasticsearch é simples a primeira vista, mas manter a estabilidade do cluster se torna cada vez mais difícil a medida que o fluxo de dados aumenta e você precisa de mais escala.


Finding a cycle in graph theory.

Question: Prove that if every vertex of a simple graph G has degree at least 2 then G contains a cycle. ( our definition says no multiple edges and no loops allowed also all simple graphs are finite by our Def'n)
Originally i tried to simply pick a vertex at random say $v_0$ then move away from it at random deleting each edge as i traversed it i made the assumption that eventually i would arrive back to a vertex that i had already been at and i would have a circuit.
Then if this vertex i landed on a second time was $v_0$ i am done and have a cycle.   If it is not a cycle i wished to delete the edge $v_0v_1$ where $v_1$ was the first vertex i moved to and proceed in this fashion until whatever vertex i started on i also ended on then claim that this was in fact a cycle.
For some reason that i dont understand this doesn't actually work.
Any ideas how to solve this would much appreciated.
Comment: Your graoh has to be finite for this to have any chance of being true.
Comment: What leads you to conclude that it "doesn't actually work"?
Comment: My prof said it didn't work i dont even know why it doesn't work =(
Something about having things of degree 1 after i left the first vertex.
Answer: Your method of random walking should discover a cycle in a finite simple graph of minimum degree $2$, although it may not include the starting vertex.
Eventually, because there only a finite number of edges, you will reach a point where no further steps are possible. At that point you have arrived at a vertex that you visited previously. The portion of the route from your previous visit to that vertex and the end point is a cycle.
Restarting the process is unnecessary, though; continuously following edges (without using any edge twice) until there are no possible next steps is sufficient.

Here the initial node $1$ is not part of any cycle but the walk ends at the vertex here marked $3$, so $3{-}4{-}5{-}6$ is the cycle discovered.
Comment: thats what i thought :s
Comment: @Faust7 Possible your prof thought you were claiming that the original vertex was in that cycle, which is not at all guaranteed. There may well be vertices in such a graph that are not on any cycle.
Comment: is there anthor simple way to solve it?

Finding a cycle in graph theory.


how to set title in a for-loop using vue.js in this example?

Question:   <template v-for="item in job">

          [[ i.node.name ]]

  </template>

I am trying to set the title for each td - but instead the title is literally being set to [[ i.node.name ]] as string rather than the value.
note:  [[ i.node.name ]]  prints the value so I know it is correct, I must be using wrong syntax for the title though.
also side note: I'm using [[ ]] as delimiters in vue.js
Comment: I am using [[ ]] delimiters though
Comment: It's `{{ }}` not square brackets.
Comment: you cant, see the documentation here:
https://vuejs.org/v2/guide/syntax.html#Text
Remember you are interpolating data into a template it's not vanilla JS.
Answer: You need to remove the brackets from your title and add a colon : in front of the title. Take a look at https://v2.vuejs.org/v2/guide/syntax.html#Attributes
  <template v-for="item in job">

              [[ i.node.name ]]

      </template>


Como recuperar a quantidade de caracteres via expressão regular?

Question: Como saber a quantidade de caracteres repetidos (exemplo: Goiaba = 2 letras a), caracteres consecutivos (sequencia de letras abc..) e números consecutivos (exemplo: 12345..) dentro de uma palavra, utilizando expressão regular? Isso é possível?
Comment: Exemplo em javascript: `'teste'.match(/e/g).length` retorna 2 pois tem duas letras `E`
Comment: Correto @WallaceMaxters é exatamente isto.
Comment: Eu já tenho algo desse tipo: [Clique Aqui!](http://jsfiddle.net/fs3eu10x/), mais mesmo assim não esta funcionando direito.
Comment: É PHP ou javascript ?
Comment: A função que estou fazendo é em JavaScript.
Comment: Você não vai conseguir fazer isso sem restringir a uma letra específica, como o Wallace fez.
Answer: Com expressões regulares não deve ser possível fazer isso como citado na resposta  do Miguel Angelo, porém, através de um loop você pode obter a quantidade de ocorrências dos caracteres e armazená-los em um array associativo.
var str = "Goiaba";
var ocorrencias = {};

for(var i = 0; i < str.length; i++) {
    var n = str[i];
    ocorrencias[n] = ocorrencias[n] ? ocorrencias[n] + 1 : 1;
}
console.log(ocorrencias); // {G=1, o=1, i=1, a=2, b=1}

DEMO
Para deixar mais bonito e organizado faça isso em uma função:
function retornarOcorrencias(str){
    var ocorrencias = {};
    for(var i = 0; i < str.length; i++){
        var n = str[i];
        ocorrencias[n] = ocorrencias[n] ? ocorrencias[n] + 1: 1;
    }
    return ocorrencias;
}

var str = 'Goiaba';
var num = '001549954607410';

var strItens = retornarOcorrencias(str);
var numItens = retornarOcorrencias(num);

console.log(strItens); // {G=1, o=1, i=1, a=2, b=1}
console.log(numItens); // {0=4, 1=2, 4=3, 5=2, 6=1, 7=1, 9=2}

DEMO
Para verificar o número de ocorrências de um caractere em particular:
console.log(strItens['a']); // 2

Nas respostas abaixo mostra como fazer isso em PHP:

Como retornar palavras mais comuns de um texto com PHP?
Comparando string no php
Comment: eu fiz algumas modificações aqui e a função funcionou perfeitamente, agradeço por sanar a minha duvida vlw!.
Answer: Acho que não tem jeito de fazer isso com RegExp.
Vai ai um JavaScript pra detectar pontos duplicados na sua string.
Vê ai se te serve:
function DetectarRepeticoes(str) {
    var obj = {};
    for (var itL = 1; itL <= str.length; itL++) {
        for (var itS = 0; itS <= str.length - itL; itS++) {
            var seq = str.substr(itS, itL);
            obj[seq] = obj.hasOwnProperty(seq) ? obj[seq]+1 : 1;
        }
    }
    var res = {};
    for (var k in obj) {
        if (obj.hasOwnProperty(k) && obj[k]>1)
            res[k] = obj[k];
    }
    return res;
}

Exemplo de uso:
DetectarRepeticoes("Miguel Angelo Santos Bicudo");

Retorno:
{
    " ": 3,
    e:   2,
    el:  2,
    g:   2,
    i:   2,
    l:   2,
    n:   2,
    o:   3,
    u:   2
}

Nota: este método é de ordem de n2, onde n é o número de caracteres da string... então não é lá muito eficiente. Mas se for usar com strings pequenas é aceitável... até unas 1000 caracteres acho que ainda fica bom na maioria dos casos.


The form $xy+5=a(x+y)$ and its solutions with $x,y$ prime

Question: In another question I was asking if there are any different $x,y>2$ primes such that $xy+5=a(x+y)$.
Where $a=2^r-1$, and $r>2$.
I was thinking if it is able to find a Pell equation or a similar pattern of $xy+5=a(x+y)$ to say what are and how many integer solutions are there (in particular prime solutions).
Thanks.
Answer: $xy-5=a(x+y)$ can be rewritten as $$(x-a)(y-a)=a^2+5$$ so for any fixed $a$ solving it just amounts to finding all the ways to factor $a^2+5$. So how many solutions depends on the prime factorization of $a^2+5$. I don't think there will be any formula for how many of those solutions have $x$ and $y$ prime.
Comment: I'm really sorry but I made a change in the question, it is not really different but it should be assumed that the -5 that I wrote is +5.
Comment: So $xy+5=a(x+y)$ can be rewritten as $$(x-a)(y-a)=a^2-5,$$ right?
Comment: true (need to spend letters)
Comment: So then what more could one do by way of an answer to your question?
Comment: If there aren't such prime pairs solve this equation, it seems very interesting. The question here if it may be unique. If when we change -5 into some other -prime will give no prime solutions. In this form of the equation we can say that for each such $a$ there are finitely (but more than 0) solutions in integers and infinitely in the union set.
Comment: So what makes you think there aren't any primes that solve the equation? $x=7$, $y=37$, $a=6$; $x=11$, $y=47$, $a=9$; $x=13$, $y=151$, $a=13$; $x=19$, $y=337$, $a=18$; $x=29$, $y=47$, $a=18$; and so on, and so on, and so forth.
Comment: Even if you insist on $a=2^r-1$ I believe there are solutions. Try $x=17179929661$, $y=4880269588100161$, $a=17179869183$.
Comment: I agree, thank you very much. It's fast seen that the number of such pairs up to n is less than ln(n). Do you think there are infinitiely many or finitely many?
Comment: My intuition says infinitely many, but my calculations show they are very rare, so I really don't know what to think.
Comment: These does not need to be common to be infinitely many..


Evaluate integral with complex exponential. Inverse Fourier transform.

Question: I'm trying to follow and understand a bigger problem in the book but at one step they simply write out the answer of this integral and take it as a given but it seems to be tricky to compute this integral. I have $g(\omega)=2a/((\omega^2+a^2)(\omega^2+b^2))$ where $a,b>0$ and I want to evaluate
$$\int\limits_{-\infty}^{\infty}g(\omega)e^{j\omega \tau} \ d\omega.$$
This is supposed to evaluate to
$$\frac{1}{(a^2-b^2)b}\left(ae^{-b|\tau|}-be^{-a|\tau|}\right).$$
Anyone who has a trick up their sleeve? I'm pretty sure it's possible to rewrite $g(\omega)$ in a way that allows us to use some neat trick.
Comment: Contrary to popular belief, there are no tricks in mathematics. There are rules, e.g. those for addition of fractions, people learn them in primary school, or never. One of them would be $$\frac1{(\omega^2+a^2)(\omega^2+b^2)}=\frac1{a^2-b^2}\left(\frac1{\omega^2+b^2}-\frac1{\omega^2+a^2}\right).$$
Answer: By partial fraction decomposition, we have $$g(\omega)=\frac{2a}{(\omega^2+a^2)(\omega^2+b^2)} = \frac{2a}{b^2 - a^2}(\frac{1}{\omega^2 + a^2} - \frac{1}{\omega^2 + b^2}) = \frac{2a}{b^2 - a^2}(\frac{1}{2ia}(\frac{1}{\omega-ia} - \frac{1}{\omega+ia}) - \frac{1}{2ib}(\frac{1}{\omega-ib} - \frac{1}{\omega+ib}))$$If we define $$\mathcal{F}\{x(t)\} = X(i\omega) = \int_{-\infty}^{+\infty} x(t)e^{-i\omega t}dt$$ The inverse transform is given by $$\mathcal{F}^{-1}\{X(i\omega)\} = x(t) = \frac{1}{2\pi} \int_{-\infty}^{+\infty} X(i\omega)e^{i\omega t}d\omega$$ It's easy to show that if $x(t) = e^{-at}u(t), \ \ a\gt0$ then $X(i\omega) = \frac{1}{a+ i\omega}$. Using this result, $$\mathcal{F}^{-1}\{\frac{1}{\omega - ia}\} = ie^{-at}u(t) \\ \mathcal{F}^{-1}\{\frac{1}{\omega + ia}\} = -ie^{at}u(-t)$$We should put these facts together.
We are interested in $h(t) = 2\pi\mathcal{F}^{-1}\{g(\omega)\}$. Using linearity property, we have $$h(t) = \frac{2a\times 2\pi}{b^2 - a^2}(\frac{1}{2ia}(\mathcal{F}^{-1}\{\frac{1}{\omega-ia}\} - \mathcal{F}^{-1}\{\frac{1}{\omega+ia}\}) - \frac{1}{2ib}(\mathcal{F}^{-1}\{\frac{1}{\omega-ib}\} - \mathcal{F}^{-1}\{\frac{1}{\omega+ib}\})) = \frac{2a\times 2\pi}{b^2 - a^2}(\frac{1}{2ia}(ie^{-at}u(t) +ie^{at}u(-t)) - \frac{1}{2ib}(ie^{-bt}u(t) +ie^{bt}u(-t))) = \frac{2a\times 2\pi}{b^2 - a^2}(\frac{e^{-a|t|}}{2a} - \frac{e^{-b|t|}}{2b})$$
Also we can check the result using Mathematica. Entering
<code>Assuming[a > 0 && b > 0,
InverseFourierTransform[(2 a/((w^2 + a^2) (w^2 + b^2))) , w , t ,
FourierParameters -> {1, -1}]]
</code>
gives
$$\frac{1}{b(b^2 - a^2)}((b e^{a t} - a e^{b t})u(-t)
  +  (b e^{-a t} - a e^{-b t}) u(t))$$this can be simplified to $$\frac{1}{b(b^2 - a^2)}(be^{-a|t|} - ae^{-b|t|}) = \frac{1}{(b^2 - a^2)}(e^{-a|t|} - \frac{a}{b}e^{-b|t|})$$
which agrees with our previous result since $$h(t) = \frac{2\pi}{b^2 - a^2}(e^{-a|t|} - \frac{a}{b}e^{-b|t|})$$
Note that there are various ways for calculating $\mathcal{F}^{-1}\{\frac{1}{\omega^2 + a^2}\}$. See for example this and this.
Comment: Wonderful, thanks!
Comment: @Parseval You're welcome.


Are associative networks still pertinent for data mining applications?

Question: Back in the 1990s, network topologies like Bidirectional Associative Memory and Hopfield Nets were all the rage.  Largely, these were billed as having energy states and recurrents that would help them learn/store and recall specific patterns readily.
These topologies are perhaps less pertinent now, but I'm wondering if they are still an optimal way to approach data mining?  They seem like they would be pertinent for things like contextual analysis in NLP, with a network trained to observe what it has "seen" before.  Will these topologies come back in, or have they been replaced by options with better accuracy rates?
Answer: Things have evolved, not necessarily changed. Now there is great emphasis in
Boltzmann Machines (BMs) and Restricted Boltzmann Machines (RBMs) that are
stochastic, generative counterparts to Hopfield networks. It would also be
important to mention Markov Random Fields (MRFs) in this list although it is a
relatively more general concept. Boltzmann Machines have received a lot
attention recently because they are an important building block for Deep
Learning.
So, to answer your question, are they pertinent? Yes, definitely. Are things the
same than back in the 90s? No, absolutely not, things have evolved quite a bit.


Rotas no Angular 2+

Question: Minha aplicação começa no componente LoginComponente:
bootstrap: [LoginComponent]

No meu login routing module eu defini as seguintes rotas:
const loginRoutes: Routes = [
  {path: 'dash', component: DashboardComponent},
  {path: 'registrar', component: RegistrarComponent},
];

@NgModule({
  imports:[RouterModule.forRoot(loginRoutes)],
  exports: [RouterModule]
})

A Dash deve ser acessada quando o usuário faz o login;
No meu login.component.html eu defini um ngIf que só vai aparecer a dash quando o usuário loga no sistema:

Neste template eu defini o router-outlet e botões para as chamadas das navegações:

     <button type="submit" routerLink="/dash" name="entrar" (click)="fazerLogin()" class="btn btn-success waves-effect" id="login-button">Entrar</button>
     <button type="button" routerLink="/registrar" class="btn btn-outline-success waves-effect">Registrar</button>

<router-outlet></router-outlet>

Tudo funciona perfeitamente por enquanto. Quando a aplicação está no localhost:4200 ela redireciona para a página de login. Quando clica em registrar ela altera para o componente de registro e quando clico em entrar ele me move para a tela de dash.
O problema é que a dash é um componente fixo que dentro dela vai ter outros componentes, então eu tentei colocar outro router-outlet dentro da dash:
   <router-outlet></router-outlet>

dashboard.routing.module.ts:
const dashboardRoutes: Routes = [
  { path: '', component: BemvindoComponent },
];

Porém, o BemVindoComponent não aparece dentro da minha dash.
Ele já está como exports e é importado pelo meu módulo de rotas da dash.
Answer: Você tem de colocar um nome ao segundo router-outlet
<router-outlet name="nomeASerDado"></router-outlet>

Ao definir nas rotas, especificar o outlet desejado
{path: 'caminho/a/ser/seguido', component: ComponenteQueSeraCarregado, outlet: 'nomeASerDado'}

E para fazer as alterações de rota, tem duas formas:

No HTML, através do routerLink

Através de um comando ao router
router.navigate([{outlets: {primary: 'caminho/da/view/primaria', nomeASerDado: 'caminho/da/view/auxiliar'}}]);

Mas você só precisa usar essa forma de alteração de rota se precisar usar o outlet nomeado, caso contrário, pode usar assim:
routerLink="caminho/a/ser/seguido"

ou assim
router.navigate(['caminho/a/ser/seguido'])

Você pode tirar mais alguma ajuda deste link.
Comment: Alterei para:   {path: 'dash', component: DashboardComponent, outlet:'primario'},
  {path: 'registrar', component: RegistrarComponent, outlet:'primario'} e
Entrar
Registrar
Ainda não deu certo
Comment: Você tem que colocar o atributo name no router-outlet e registrar a rota no módulo de roteamento
Comment: coloquei também...
Comment: O routerLink no botão não está entre colchetes. Deveria ficar `[routerLink]=`
Comment: usando com colchetes a página nem carrega... e sem colchetes não funciona
Comment: Nos botões, o valor do atributo `routerLink` não está fechado corretamente. Você não fechou o `outlets` e nem o `[{`
Comment: Corrigi. agora a página carrega, mas o meu bemvindo component ainda não carrega dentro do segundo router-outlet. O primeiro eu defini como name "primario", o segundo deixei só router-outlet. Preciso nomear este também?
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/80348/discussion-between-mutlei-and-leticia).

Rotas no Angular 2+


Campos na mesma linha Bootstrap aplicação MVC5

Question: Gostaria de uma dica de como colocar dois campos na mesma linha no Razor, usando o bootstrap em uma aplicação ASP.NET MVC5.
div class="ibox-content">
                            <form role="form" class="form-inline">

                                    @Html.LabelFor(model => model.Nm_EquipeMinima, new { @class = "control-label col-md-2" })

                                        @Html.EditorFor(model => model.Nm_EquipeMinima)
                                        @Html.ValidationMessageFor(model => model.Nm_EquipeMinima)

                                    @Html.LabelFor(model => model.Nr_EquipeMinima, new { @class = "control-label col-md-2" })

                                        @Html.EditorFor(model => model.Nr_EquipeMinima)
                                        @Html.ValidationMessageFor(model => model.Nr_EquipeMinima)

                            </form>

Este é o meu código e abaixo o resultado.
Answer: No Bootstrap, tenha em mente que o todo espaço é divisível por 12 ou múltiplos de 12.
Quando você faz:

    @Html.LabelFor(model => model.Nm_EquipeMinima, new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.Nm_EquipeMinima)
        @Html.ValidationMessageFor(model => model.Nm_EquipeMinima)

Seu form-group ocupa os 12 espaços. Seu label ocupa 2 espaços (@class = "col-md-2") e seu @Html.EditorFor ocupa 6 espaços (div class="col-md-6"). Ainda sobrariam 4 espaços para colocar mais alguma coisa na linha.
A forma de fazer isso é colocando todos os componentes dentro do mesmo form-group, assim:

    @Html.LabelFor(model => model.Nm_EquipeMinima, new { @class = "control-label col-md-1" })

        @Html.EditorFor(model => model.Nm_EquipeMinima)
        @Html.ValidationMessageFor(model => model.Nm_EquipeMinima)

    @Html.LabelFor(model => model.Nr_EquipeMinima, new { @class = "control-label col-md-1" })

        @Html.EditorFor(model => model.Nr_EquipeMinima)
        @Html.ValidationMessageFor(model => model.Nr_EquipeMinima)

Repare que tenho dois label com col-md-1 e duas div com col-md-5. Seria 1 + 1 + 5 + 5 = 12. Ou seja, coloco assim todos os campos na mesma linha ocupando os 12 espaços disponíveis pelo framework.
Veja uma explicação sobre o sistema de grids aqui.
Answer: Erison, fiz algumas pequenas alterações no seu html, onde adicionei um div com class row e os divs onde eram form-group coloquei col-md-6, acredito que isso seja o suficiente no seu caso.
Você pode ver melhor sobre o uso dos col-... no link

    <form role="form" class="form-inline">

                @Html.LabelFor(model => model.Nm_EquipeMinima, new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Nm_EquipeMinima)
                    @Html.ValidationMessageFor(model => model.Nm_EquipeMinima)

                @Html.LabelFor(model => model.Nr_EquipeMinima, new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Nr_EquipeMinima)
                    @Html.ValidationMessageFor(model => model.Nr_EquipeMinima)

    </form>

Comment: mas o label fica em cima do input, então seria só mudar o div col-md-6 para 12 e tirar o form-inline ai fica bonitão :)
Comment: Nas `divs` de dentro, ainda tem mais 4 espaços cada que podem ser utilizados. Desta forma fica meio feião porque os blocos ficarão alinhados à esquerda.


How to verify if an e-mail was really sent?

Question: A customer states that an email was received from Bob. Bob claims that the email was never sent.
How can I verify which side is lying? If both sides have on-premises email servers (e.g. Exchange Server), is this even possible?
EDIT
I'm assuming both parties have motivation and possibly skills to tamper the server
Comment: https://docs.microsoft.com/en-us/exchange/mail-flow/transport-logs/search-message-tracking-logs?view=exchserver-2019
Answer: You can prove it from your side.
You didn't specify what version of Exchange you're running, but you can perform a message trace in Exchange to search for all emails sent by Bob. If you don't see the email in question then Bob didn't send it via your Exchange server.
That's not to say that Bob didn't send the customer an email form another email server/provider.
Comment: What if he did? As in, "What if Bob had access to the mail server, could be expunge his activity?" - Yes, he could, by deleting the relevant tracking logs. If this is the case then you could ask the recipient's Exchange administrator(s) to check their message tracking logs for the email from Bob.
Comment: What if Bob had access to the mail server?
Answer: You can check that on any of the servers. Their logs will indicate if it was sent/received. Specifically, you can check in Exchange Message Tracking, as long as you have it enabled.
For the receiving part:
If the email appears in message tracking on your Exchange Server as "message delivered locally to store...", it proves the emails were delivered to the respective inboxes.
In a similar manner, for the sending part, you can check the message tracking (which will give you timestamp, user and subject).


Como faço para o link de imag map ser um parâmetro vindo da base de dados?

Question: Gostaria que na tag área do imag map no atributo href em vez de colocar o link da pagina eu quero que receba um parâmetro que seja enviado a um método c#.
Codigo HTML

    <map name="Cores">
        <area  shape="rect" alt="Rosa" coords="8,8,96,116" href="<%#Eval("")%>">
         <area  shape="rect" alt="Rosas" coords="111,12,201,105" href="#"/>
        <area  shape="rect" alt="Rosa" coords="208,8,307,109" href="#"/>
        <area  shape="rect" alt="Rosa" coords="312,11,406,111" href="#"/>
        <area  shape="rect" alt="Rosa" coords="415,10,509,109" href="#"/>
        <area  shape="rect" alt="Rosa" coords="515,12,606,107" href="#"/>
        <area  shape="rect" alt="Rosa" coords="9,115,102,213" href="#"/>
        <area  shape="rect" alt="Rosa" coords="108,116,197,209" href="#"/>
        <area  shape="rect" alt="Rosa" coords="210,114,298,208" href="#"/>
        <area  shape="rect" alt="Rosa" coords="311,114,402,210" href="#"/>
        <area  shape="rect" alt="Rosa" coords="416,115,508,213" href="#"/>
        <area  shape="rect" alt="Rosa" coords="514,115,602,213" href="#"/>
        <area  shape="rect" alt="Rosa" coords="110,222,204,319" href="#"/>
        <area  shape="rect" alt="Rosa" coords="313,115,403,207" href="#"/>

         <area  shape="rect" alt="Rosa" coords="6,220,100,317" href="#"/>
        <area  shape="rect" alt="Rosa" coords="210,221,298,314" href="#"/>
        <area  shape="rect" alt="Rosa" coords="313,222,401,316" href="#"/>
        <area  shape="rect" alt="Rosa" coords="412,220,505,319" href="#"/>
        <area  shape="rect" alt="Rosa" coords="515,219,602,316" href="#"/>
        <area  shape="rect" alt="Rosa" coords="7,327,92,419" href="#"/>
        <area  shape="rect" alt="Rosa" coords="109,329,198,422" href="#"/>
        <area  shape="rect" alt="Rosa" coords="514,223,603,421" href="#"/>

        <area  shape="rect" alt="Rosa" coords="209,329,295,420" href="#"/>
        <area  shape="rect" alt="Rosa" coords="313,327,402,417" href="#"/>

        <area  shape="rect" alt="Rosa" coords="414,330,504,421" href="#"/>

        <area  shape="rect" alt="Rosa" coords="512,329,600,220" href="#"/>
    </map>

C#
public static DataTable GetProdutosInAtributos(string categoriaID, string pageNumber, out int howManyPages)
       {
      *DbCommand comm = GenericDataAcess.CreateCommand();
       comm.CommandText = "GetProdutoinAtributos";
       //cria um novo parametro
       DbParameter param = comm.CreateParameter();
       param.ParameterName = "@atributoValueID";
       param.Value = categoriaID;
       param.DbType = DbType.Int32;
       comm.Parameters.Add(param);*

//É AQUI QUE EU TENHO O PARAMETRO @atributoValueID
       //cria um novo parametro
       param = comm.CreateParameter();
       param.ParameterName = "@DescricaoTamnaho";
       param.Value = TendenciasConfigurations.ProdDescricaoTamnaho;
       param.DbType = DbType.Int32;
       comm.Parameters.Add(param);

       //cria um novo parametro
       param = comm.CreateParameter();
       param.ParameterName = "@Numpagina";
       param.Value = pageNumber;
       param.DbType = DbType.Int32;
       comm.Parameters.Add(param);

       //cria um novo parametro
       param = comm.CreateParameter();
       param.ParameterName = "@ProdutosPorPagina";
       param.Value = TendenciasConfigurations.ProdutosPorPagina;
       param.DbType = DbType.Int32;
       comm.Parameters.Add(param);

       //cria um novo parametro
       param = comm.CreateParameter();
       param.ParameterName = "@HowManyProducts";
       param.Direction = ParameterDirection.Output;
       param.DbType = DbType.Int32;
       comm.Parameters.Add(param);

       //executa a stored procedure e salva os resultados no datatable
       DataTable tabela = GenericDataAcess.ExecuteSelectCommand(comm);
       //calcula quantas paginas por produtos e define o parametro de saida
       int howmanyProducts = Int32.Parse(comm.Parameters["@HowManyProducts"].Value.ToString());
       howManyPages = (int)Math.Ceiling((double)howmanyProducts / (double)TendenciasConfigurations.ProdutosPorPagina);

       //retorna a pagina dos produtos
       return tabela;
   }

Comment: Ainda não deu pra entender qual a sua dúvida. Tens como tentar ser mais claro? Você pode melhorar sua pergunta clicando em [edit]
Comment: na minha pagina web eu quero usar uma imagMap para linkar  cores, que estão amazenadas na base de dados sql, eu armazeno o id da cor em um parametro. eu quero saber como posso linkar o imagmap com a cor armazenada na base de dados
Comment: Como você está recuperando seus dados da base, tem como posta o que você já fez? e sua imagMap  como esta ?
Answer: Dependendo do que você deseja fazer, você pode usar requisição ajax, ou seja, na sua tag  você teria o evento html onclick que chamaria uma função javascript, que por fim chamaria seu método c# através de um serviço.
Ficaria mais ou menos assim:
Página:
<map name="Cores">
    <area shape="rect" alt="Rosa" coords="8,8,96,116" onclick="teste('<%= valor1 %>');">
</map>

//Obs: valor1 é uma variável que eu criei no c#, use a sua. Lembrando que deve ser pública, você também pode acessar um método que retorna algo ao invés da variável. Exemplo <%= MetodoRetornaAlgo() %>.

Página backend:
public partial class Index : System.Web.UI.Page
{
    public String valor1 = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        valor1 = "Parametro1";
    }

    [WebMethod]
    public static void Teste(string valor)
    {
        //Fal algo
    }

}

Comment: Obrigada @Guilherme Guini
Comment: eu acho que estou a fazer algo errado! tal como voçê apresentou eu fiz exatamente assim , Mas o link do imagMap nem esta a funcionar ! por outra eu estou a usar um userControl , nesta linha eu substituo url: '**Teste.aspx**/Teste', pelo nome do userControl onde esta o metodo certo?
Comment: Veja a alteração da minha resposta!


Tabledrag in grid shape for media form field widget thumbnails

Question: I am looking for a way to change the tabledrag into a grid shape. A nice looking solution for drag-and-drop uploading files and sorting them in a way that jquery sortable does. It should end up to be something like the uploaded thumbnails in Facebook's status update form.
Looks like I'll end up writing a custom solution from scratch like the one here: jQueryUI Sortable + HTML5 File API examples?
Can you show me a starting point or do you know about any work has been done so far?
Comment: Here are some modules that support this behavior:
https://www.drupal.org/project/nice_imagefield_widget
https://www.drupal.org/project/dragndrop_upload
https://www.drupal.org/project/media_gallery
Answer: Plup seems a good place to start altough it looks abandoned.

Additionally there is this wiki page for comparison of similar modules.


Could adding more history (expanding the training sample) reduce forecast accuracy?

Question: Following up on a discussion in a previous thread:
Are there any situations where adding too much data to a forecasting model is counterproductive, in the sense that it reduces the forecasting accuracy of the model?
Specifically, if I have a univariate time series model, is there such thing as using too much history? Are there situations where I have 20 years of monthly data, but I would be better off using only the most recent 5 years of data, since older data would reduce the accuracy of the model.
For example if there was a structural break in the time series, does feeding data from before the break to the time series somehow throw the model off?
Or does the ML truism that "more data = better accuracy" hold for time series as well?
Comment: @RichardHardy https://stats.stackexchange.com/questions/343848/is-modelling-a-structural-change-in-a-time-series-useful-for-statistical-forecas
Comment: As always, it depends.  Often some pieces of data are of lower quality than others: throwing lots of low-quality data at a problem does not necessarily improve the solution.
Comment: Do you mean adding new variables or increasing the sample size of the existing variables?
Comment: @RichardHardy increasing the sample size. See edit.
Answer: If the time series data are coming from an unchanging data generating process (DGP), having a longer time series (larger sample size) can only be beneficial. Most models will be fit with greater accuracy on more data and thus will generate better forecasts. (A counterexample would be a spurious regression model for a pair of random walks. There, having a larger sample will not necessarily lead to a better estimate of the slope that is actually zero. Hence, if the model is terrible to begin with, a longer sample might not help in improving it.)
If the time series are coming from a DGP that is evolving over time and the model does not account for that, more data may either be beneficial or detrimental. A longer history may be a more irrelevant history to the extent that it would harm forecasting performance. This depends on how quickly the DGP is changing and how much history you already have, and how much more history you are adding.

[D]oes feeding data from before the break to the time series somehow throw the model off?

Yes, it very well may, unless the break is minuscule and the historical data is relevant enough for the new period.
Comment: +1 A formal approach that considers whether adding observations prior to a structural change improves the forecasts or not is: Pesaran MH, Timmermann A (2002). "Market Timing and Return Prediction under Model Instability." _Journal of Empirical Finance_, **9**, 495–510. [doi:10.1016/s0927-5398(02)00007-5](https://doi.org/10.1016/s0927-5398(02)00007-5)
Answer: Thanks for the question as it leads to a teaching moment ....
An often overlooked caveat when dealing with data is the assumption that the parameters to be optimized are invariant . In practice with time series data , the question should be asked "have the parameters changed over time" or equivalently do we have too much data ?. Tong in 1980 considered this issue

with the following idea in mind
.
Following is a data set from his work suggesting how to deal with this issue.

with acf here

If one identified a model based upon the 40 values, we get

and a residual plot of

The residual plot suggests model deficiency which might be treated by incorporating variance change detection ala Tsay: Outliers, Level Shifts, and Variance Changes in Time Series  or more simply parameter change detection via a sequential use of the Chow test for constant parameters  where the grouping is based upon a search.
The acf of the residuals does not warn us about the violation.

If we estimate the AR(1) model separately for different possible grouping, we get

suggesting the optimal partitioning is 1-22 vs 23-40.

The two separate estimations are here

and here

As to whether or not the segmentation (discarding the first 22 observations) yields a more accurate prediction of some future values is unknown as it all depends on the origin of the forecast, the length of the forecast and the dictatorial impact of these future values. As they say, "Results may vary!" as only your data knows whether or not your analysis has been correctly/sufficiently accomplished. All I know is that one needs to know and test the assumptions of any model imposed on the data.
If one simulates an ar(1) process with a value of .9 and then follows with realizations from a process using -.9 ... we globally conclude using the ensemble that the series is free of auto-correlation which is quite flawed.


Example of a subalgebra of infinite-generated algebra which cannot be extended to a maximal subalgebra

Question: First of all, sorry for my English, especially mathematical one. The problem is that I know how to call such things in Ukrainian but unfortunately did not manage to find proper translations to English. So, I will give some brief definitions of terms in order to not confuse you with the names.
So, an algebra (maybe, partial) is a set of elements together with a set of operations defined on these elements $ (A, \Omega) $.
Let $ B \subset A $. Then a closure $[B]_f$ of $A$ by an $n$-ary operation $f \in \Omega$ is a set defined by two rules:

$ B \subseteq [B]_f$
$ \forall (a_1, a_2, \ldots, a_n) \subset [B]_f $  if  $f(a_1, a_2, \ldots, a_n)$ is defined  then $f(a_1, a_2, \ldots, a_n) \in [B]_f$

A closure $[B]$ of $A$ is $ B^0 \cup B^1 \cup B^2 \ldots $ where $B^0 = B$, $B^{i+1} = \bigcup_{f \in \Omega}[B^i]_f$.
The definition of subalgebra and therefore algebra extension is obvious, I think.
$B$ is a system of generators (I believe, it is close to the basis) for algebra $(A,\Omega)$ if $[B] = A$.
And, finally, subalgebra $(B,\Omega)$ is called maximal subalgebra of $(A,\Omega)$ if there is no subalgebra $(C,\Omega)$ such that $B \subset C \subset A, B \neq A, C \neq A, C \neq B$.
It can be proved that for a algebra with existing finite system of generators each its subalgebra can be extended to some maximal subalgebra.
But for algebras with infinite systems of generators, this statement is not always true. And I need a counter-example. Therefore, I need an example of infinite-based algebra and a subalgebra which is impossible to extend to some maximum subalgebra.
Comment: Unfortunately, every proper subspace $W$ of a vector space $V$ is contained in a maximal (I assume by this you also mean it doesn't equal the whole thing) subspace; just take a vector $v \in V$ not in $W$, let $B$ be a basis of $W$, extend $B \cup \{ v \}$ to a basis of $V$, and consider the span of this basis minus $v$.
Comment: Anyway, I would recommend you try thinking about groups instead of vector spaces. In fact there is a relatively straightforward example of an abelian group which has no maximal proper subgroups whatsoever.
Comment: I thought about infinite-based vector spaces and replacements of all vectors with i-th coordinate equal to some number (maybe, to all numbers <=i) for each i, but I didn't manage to come up with something.
Comment: Your "creators" are usually called "generators".
Comment: @g.castro: thanks
Comment: @QiaochuYuan: Thank you, I will think of it.
Comment: @QiaochuYuan: I believe, you mean an additive group of rational numbers which does not have maximal subgroups at all.
Answer: EDITED: Hint: Consider the operation $f(n) = n-1$ on the natural numbers (with $f(0)$ arbitrary).
The original hint (Consider an algebra without any operations, or with only a trivial operation) was completely wrong.
Comment: Hm, identity operation cannot give you any new elements. This means, that if you have a system B, then the closure of this system  by identity operation would give you B again. This in turn means that adding new elements to B means nothing but adding new elements, so if you just take any subset B of algebra base A, you can add all but one of the A\B elements to B and you will get a maximal subalgebra. I believe, that very alike thought have place with constant operation. Where am I wrong?
Comment: This one seems to be really cool and easy to understand! Thanks!
Comment: I'm willing to edit your answer in purpose to add a full proof. Please, respond if it is okay. Or, if you would like, you can do it by yourself.
Comment: Sure, go ahead.
Comment: Not sure if my edit is just dismissed or I did something wrong. However, [here](http://skitch.com/ikostia/8fg81/skitch) is the screenshot of the proof.
Answer: The answer is an abelian group of rational numbers $Q$. It has no maximal subgroups at all. Proof can be found here.
Thanks, Qiaochu Yuan, for the direction.


Accesing Individual Frames using AV Player

Question: In a recent project, I have to access all frames of my video individually using AV Foundation. Also, if possible to acess them randomly (like an array)
I tried to research the question but I didn't get anything useful.
Note: Is there any useful documentation to get familiar with the AV Foundation ?
Comment: I can answer you for any question. But you have to explain more your question/Problem..
Comment: The problem is that I don't know how to access individual frames of my video. Because I need to apply some magic algorithm in each frame by itself.
Comment: you want to play video in different frames???
Comment: yes, I got it now. You want to access frames of videos. right??
Comment: You will get images.
Comment: Yes you are right, I want to acess frames of videos.
Answer: You can enumerate the frames of your video serially using AVAssetReader, like this:
let asset = AVAsset(URL: inputUrl)
let reader = try! AVAssetReader(asset: asset)

let videoTrack = asset.tracksWithMediaType(AVMediaTypeVideo)[0]

// read video frames as BGRA
let trackReaderOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings:[String(kCVPixelBufferPixelFormatTypeKey): NSNumber(unsignedInt: kCVPixelFormatType_32BGRA)])

reader.addOutput(trackReaderOutput)
reader.startReading()

while let sampleBuffer = trackReaderOutput.copyNextSampleBuffer() {
    print("sample at time \(CMSampleBufferGetPresentationTimeStamp(sampleBuffer))")
    if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
        // process each CVPixelBufferRef here
        // see CVPixelBufferGetWidth, CVPixelBufferLockBaseAddress, CVPixelBufferGetBaseAddress, etc
    }
}

Random access is more complicated. You could use an AVPlayer + AVPlayerItemVideoOutput to get frames from any time t, using copyPixelBufferForItemTime, as described in this answer, but the subtlety lies in how you choose that t.
If you want to sample the video at uniform intervals, then that's easy, but if you want to land on the same frames/presentation time stamps that the serial AVAssetReader code sees, then you will probably have to preprocess the file with AVAssetReader, to build a frame number -> presentation timestamp map. This can be fast if you skip decoding by using nil output settings in AVAssetReaderTrackOutput.
Comment: Does this give all frames of my video ?
Comment: The `AVAssetReader` method does. If you know all the frame timestamps, the "random access" method should too.
Comment: Thanks, that's very helpful. One question(s), can you provide with a documentation about  CMSampleBufferGetImageBuffer because I still don't get it. Also, is there a way to save locally them so that I check what is happenning ?
Comment: There's some info in the `CMSampleBuffer` header file. It returns a `CVPixelBufferRef` from which you can get width, height and a pointer to pixels. See http://stackoverflow.com/q/8072208/22147  for `CVPixelBuffer`->`UIImage`.
Comment: Thanks. If I have any problem I will write to you.
Comment: Hi Fistman, I have another question please. For the AVAssetReader is meant for offline (not real time) what about getting them in real time ?
Comment: What do you mean by realtime?
Comment: Assume I have a video on a server and I can play it on a local player. What I need is to acess its frames on real time (while it is playing for example) and apply some magic on it.
Comment: AVAssetReader only does local files, so you need AVPlayer + videooutput.
Comment: Can you explain how to do so please ? And if you have any documentation about it please let me know.
Comment: The explanation is in the answer? Maybe start a new question with these new details.
Answer: If you need to get the current frame while playing the video you could add an observer for the player and could get the current frame like this:
var player: AVPlayer?
var playerController = AVPlayerViewController()
var videoFPS: Int = 0
var currentFrame: Int = 0
var totalFrames: Int?

func configureVideo() {
    guard let videoURL = "" else { return }
    player = AVPlayer(url: videoURL)
    playerController.player = player
    guard player?.currentItem?.asset != nil else {
        return
    }
    let asset = self.player?.currentItem?.asset
    let tracks = asset!.tracks(withMediaType: .video)
    let fps = tracks.first?.nominalFrameRate

    self.videoFPS = lround(Double(fps!))
    self.getVideoData()
}

func getVideoData() {
    self.player?.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1,timescale: Int32(self.videoFPS)), queue: DispatchQueue.main) {[weak self] (progressTime) in

        if let duration = self!.player?.currentItem?.duration {

            let durationSeconds = CMTimeGetSeconds(duration)
            let seconds = CMTimeGetSeconds(progressTime)
            if self!.totalFrames == nil {
                self!.totalFrames = lround(Double(self!.videoFPS) * durationSeconds)
            }

            DispatchQueue.main.async {
                if self!.totalFrames != self!.currentFrame {
                    self!.currentFrame = lround(seconds*Double(self!.videoFPS))
                } else {
                    print("Video has ended!!!!!!!!")
                }
                print(self!.currentFrame)
            }
        }
    }
}

After getting the current frame number, you could use AVAssetImageGenerator to retrieve the specific image.


How to maintain multiple values for key in resx file c#

Question: I want to maintain 2 values for one key like this
Key   ,              value           ,                           code
InvalidcardMessage        ,     Invalid card details           ,               4
In resx file I found only one value for key. How to maintain these values in my project globally like resource file? Is there anyway to do that?
Comment: Resx are for localizable resources, it's not a value store to save application data. If second value is a localizable item (an image, for example) you'd better to use a separate resource (instead of index). If it's just an unlocalizable index you may use an external application data file.
Comment: Do you want these values to be localizable?
Comment: yes Matthew. I want these values to be localizable.
Answer: Why not combine value and code into one string using, say, comma (',') as a separator? So in the resx file it will be
 key   = "InvalidcardMessage"
 value = "Invalid card details,4"

To get value and code all you should do is to split by comma:
  String[] values = Resources.InvalidcardMessage.Split(',');

  String value = values[0];         // "Invalid card details"
  int code = int.Parse(values[1]);  // 4


Validate Email Existence

Question: I am trying to use the "PHP SMTP Email Validation" library
On line 163 of smtp_validateEmail.class.php the $reply variable is empty.
What am I doing wrong? Has anyone gotten this to work? Is there another library I should use?
Thanks
Comment: It's hard to tell from the way you wrote your question what's going wrong. There can be numerous reasons and you did not provide much information about your problem. It can even be the case that the same problem will happen with any other library as well, so no recommendation can be given.
Answer: Not many mail servers are going to allow this sort of validation - it's far far far too easy for spammers to utterly nail a server with verification requests and build a list of valid emails they can flood with penis-pill-pushing-russian-brides-who-sell-PHDs spam.
If you're just trying to determine if an email address has a valid format, not that it actually exists, you can use
$email = filter_var($email, FILTER_VALIDATE_EMAIL);

Answer: I would say that you're not passing the $email variable to the function that creates the $user and $domain variables.
The function is _parseEmail and is defined on line 78
Are you getting any errors?
Answer: If you're trying to determine if an email is valid and exists, then send an email to it. If you've forced the user to enter in their email twice, there is really not much more you can do other than send them an authentication email and that's it.

Validate Email Existence


Inject variable into html input tag value using Html Agility Pack C#

Question: Is it possible using the C# HTML Agility Pack to insert a variable into the selected node?
I have created my HTML form, loaded it, and selected the input node that I want, and now I would like to inject in the value field a SAML Response
Here is a bit of the code that I have, first the HTML document:

    <title></title>

    <form id="frmSSO" runat="server" enableviewstate="False">

            <input id="SAMLResponse" name="SAMLResponse" type="text" runat="server" enableviewstate="False" value=""/>
            <input id="Query" name="Query" type="text" runat="server" enableviewstate="False" value=""/>

    </form>

and here is the function which loads the HTML document and selects the node I want:
public static string GetHTMLForm(SamlAssertion samlAssertion)
{
    HtmlAgilityPack.HtmlDocument HTMLSamlDocument = new HtmlAgilityPack.HtmlDocument();
    HTMLSamlDocument.Load(@"C:\HTMLSamlForm.html");
    HtmlNode node = HTMLSamlDocument.DocumentNode.SelectNodes("//input[@id='SAMLResponse']").First();

    //Code that will allow me to inject into the value field my SAML Response
}

EDIT:
Ok so I have achieved injecting the SAML Response packet into the "value" field of the html input tag with this:
HtmlAgilityPack.HtmlDocument HtmlDoc = new HtmlAgilityPack.HtmlDocument();
String SamlInjectedPath = "C:\\SamlInjected.txt";
HtmlDoc.Load(@"C:\HTMLSamlForm.txt");
var SAMLResposeNode = HtmlDoc.DocumentNode.SelectSingleNode("//input[@id='SAMLResponse']").ToString();
SAMLResposeNode = "<input id='SAMLResponse' name='SAMLResponse' type='text' runat='server' enableviewstate='False' value='" + samlAssertion + "'/>";

Now I just need to be able to add that injected tag back into the original HTML document
Comment: I'm thinking that there might be something useful in this question

http://stackoverflow.com/questions/9520932/how-do-i-use-html-agility-pack-to-edit-an-html-snippet
Answer: ok I have solved this using the following:
HtmlAgilityPack.HtmlDocument HtmlDoc = new HtmlAgilityPack.HtmlDocument();
HtmlDoc.Load(@"C:\HTMLSamlForm.html");
var SamlNode = HtmlNode.CreateNode("<input id='SAMLResponse' name='SAMLResponse' type='text' runat='server' enableviewstate='False' value='" + samlAssertion + "'/>");
foreach (HtmlNode node in HtmlDoc.DocumentNode.SelectNodes("//input[@id='SAMLResponse']"))
{
    string value = node.Attributes.Contains("value") ? node.Attributes["value"].Value : " ";
    node.ParentNode.ReplaceChild(SamlNode, node);
}

Then in order to check the contents of the new HTML file I output it using this:
System.IO.File.WriteAllText(@"C:\SamlInjected.txt", HtmlDoc.DocumentNode.OuterHtml);