Listar apenas contratos vencidos por ID e não considerar se o ID tiver contrato em vigência

Question: Fala galera...
Preciso listar apenas os contratos VENCIDOS, pois quando a empresa renova o contrato, os dados do contrato vencido (antigo) permanecem no BD com status "0". Então temos: 1 contrato vencido (antigo) e 1 em vigência (novo, que foi renovado).
E essa query tá me mostrando a empresa que tem registro de contrato vencido, porém que já tem contrato em vigência (renovado) e isso não tá certo, pois se ela já renovou o contrato, então não tem contrato vencido na data corrente e aí ela não deve aparecer na lista.
O que preciso é que me seja listada as empresas que não possuem contrato vigente e vencido.
Tentei essa query, mas não deu certo:
SELECT *

FROM contrato_empresa ce, empresas e

WHERE

e.emp_id = ce.cte_id_emp AND
ce.cte_status = 0 AND
ce.cte_dt_ini < CURDATE() AND
ce.cte_dt_fim < CURDATE()

ORDER BY e.emp_cidade ASC, e.emp_fantasia ASC

Alguém consegue me ajudar?
Obrigado!
Comment: Se você quer filtrar as empresas que não tenham contratos a vigentes e vencidos, você quer as empresas que não tenham contrato?
Comment: @Diego_F, preciso da lista apenas com contrato VENCIDO, pois quando a empresa renova o contrato, os dados do contrato vencido (antigo) permanecem no BD com status "0". Então temos: 1 contrato vencido (antigo) e 1 em vigência (novo, que foi renovado). E essa query tá me mostrando a empresa que tem registro de contrato vencido, porém que já tem contrato em vigência (renovado) e isso não tá certo, pois se ela já renovou o contrato, então não tem contrato vencido na data corrente e aí ela não deve aparecer na lista, sacou?! :)
Answer: Primeiro problema na sua query,
dentro do where existe isso ce.cte_id = ce.cte_id , qual a finalidade de comparar algo com ele mesmo?
Não tem logica,
talvez o problema seja um c a mais, ficando ce.cte_id = e.cte_id, mas ainda acredito que não exista essa verificação por não atender a segunda forma normal.
Segundo problema,
Você faz uma validação que o contrato tem data de inicio menor que a data atual, OK
ce.cte_dt_ini < CURDATE()
Mas esse contrato também precisa ter data final do contrato menor que a data atual, ou seja precisa ser ce.cte_dt_fim > CURDATE() e não ce.cte_dt_fim < CURDATE() como esta na sua query.
Sua query então deveria ficar assim
SELECT *
FROM contrato_empresa ce, empresas e
WHERE
e.emp_id = ce.cte_id_emp AND
ce.cte_status = 0 AND
ce.cte_dt_ini < CURDATE() AND
ce.cte_dt_fim > CURDATE() AND
ORDER BY e.emp_cidade ASC, e.emp_fantasia ASC

Comment: Alexandre, tua sugestão exibe os contratos dentro de vigência com status "0" e não é isso que quero. Quero a lista de contrato VENCIDO, pois quando a empresa renova o contrato, os dados do contrato vencido ficam no BD com status "0". Então temos: 1 contrato vencido e 1 em vigência (novo, renovado). E essa query tá me mostrando a empresa que tem registro de contrato vencido, porém que já tem contrato em vigência (renovado) e isso não tá certo, pois se ela já renovou o contrato, então não tem contrato vencido na data corrente, sacou?! :)
Comment: Esta difícil entender a explicação do que deseja. Entendo que um contrato é renovado no vencimento, ou após o vencimento, do contrato anterior. Dessa forma todos os contratos já vencidos obviamente estarão vencidos na data atual.
Comment: Então se vc quer uma query vencida, não precisa de data inicio, pq o importante é ser maior que a data fim
```
SELECT *
FROM contrato_empresa ce, empresas e
WHERE
e.emp_id = ce.cte_id_emp AND
ce.cte_status = 0 AND
ce.cte_dt_fim < CURDATE() AND
ORDER BY e.emp_cidade ASC, e.emp_fantasia ASC
```


'Argument list too long' error while copying a large number of files

Question: I am using the following command:
\cp -uf /home/ftpuser1/public_html/ftparea/*.jpg /home/ftpuser2/public_html/ftparea/

And I am getting the error:
-bash: /bin/cp: Argument list too long

I have also tried:
ls /home/ftpuser1/public_html/ftparea/*.jpg | xargs -I {} cp -uf {} /home/ftpuser2/public_html/ftparea/

Still got -bash: /bin/ls: Argument list too long
ANy ideas?
Comment: I am trying to copy all jpgs from 1 directory to another but only new files and ones that have been updated.
Comment: `ls` is not designed to do this kind of thing. Use `find`.
Comment: The problem isn't with ls, it is with the number of arguments the shell is passing to ls.  You'd get the same error with vi or with any non-builtin command.
Comment: But `ls` is *especially* not designed to do this: http://mywiki.wooledge.org/ParsingLs
Comment: True, but in this case the error isn't because of a parsing error with ls, it is with passing a billion arguments to a new process that happens to be ls.  In addition to being an inappropriate use of ls, it also happens to bump against a resource / design limitation of unix.  In this case, the patient has both a stomach ache and a broken leg.
Comment: Related: [Does "argument list too long"
 restriction apply to shell builtins?](https://stackoverflow.com/questions/47443380/does-argument-list-too-long-restriction-apply-to-shell-builtins)
Answer: *.jpg expands to a list longer than the shell can handle. Try this instead
find  /home/ftpuser/public_html/ftparea/ -name "*.jpg" -exec cp -uf "{}" /your/destination \;

Comment: I used find  /home/ftpuser1/public_html/ftparea/ -name "*jpg" -exec cp -uf "{}" /home/ftpuser2/public_html/ftparea/ and got the following error find: missing argument to `-exec'
Comment: You are missing the last argument of cp, the answerer told you right. Double check your implementation.
Note that in this answer the dot in "*.jpg" is missing, this could lead to misbehaviors (cp a dir named "myjpg" for example).
Note then that may be paranoic but safer to specify closely what you are going to copy using -type file (preventing dirs, symlinks and so on to be affected)
Comment: After closer inspection i missed the "\;" to finish the command that -exec should execute. Silly me!
Comment: @AlberT: thanks for the heads re the missing dot. That was a typo. Answer updated.
Comment: It's not that cp can't handle it. The shell can't.
Answer: There is a maximum limit to how long an argument list can be for system commands -- this limit is distro-specific based on the value of MAX_ARG_PAGES when the kernel is compiled, and cannot be changed without recompiling the kernel.
Due to the way globbing is handled by the shell, this will affect most system commands when you use the same argument ("*.jpg").  Since the glob is processed by the shell first, and then sent to the command, the command:
cp -uf *.jpg /targetdir/

is essentially the same to the shell as if you wrote:
cp -uf 1.jpg 2.jpg ... n-1.jpg n.jpg /targetdir/

If you're dealing with a lot of jpegs, this can become unmanageable very quick.  Depending on your naming convention and the number of files you actually have to process, you can run the cp command on a different subset of the directory at a time:
cp -uf /sourcedir/[a-m]*.jpg /targetdir/
cp -uf /sourcedir/[n-z]*.jpg /targetdir/

This could work, but exactly how effective it would be is based on how well you can break your file list up into convenient globbable blocks.
Globbable.  I like that word.
Some commands, such as find and xargs, can handle large file lists without making painfully sized argument lists.
find /sourcedir/ -name '*.jpg' -exec cp -uf {} /targetdir/ \;

The -exec argument will run the remainder of the command line once for each file found by find, replacing the {} with each filename found.  Since the cp command is only run on one file at a time, the argument list limit is not an issue.
This may be slow due to having to process each file individually.  Using xargs could provide a more efficient solution:
find /sourcedir/ -name '*.jpg' -print0 | xargs -0 cp -uf -t /destdir/

xargs can take the full file list provided by find, and break it down into argument lists of manageable sizes and run cp on each of those sublists.
Of course, there's also the possibility of just recompiling your kernel, setting a larger value for MAX_ARG_PAGES.  But recompiling a kernel is more work than I'm willing to explain in this answer.
Comment: I have no idea why this was down-voted.  It's the only answer that seems to be explaining why this is happening.  Maybe because you didn't suggest using xargs as an optimization?
Comment: added in the xargs solution, but i'm still worried the downvotes are because of something blatantly wrong in my details and noone wants to tell me what it is. :(
Comment: `xargs` seems to be much more efficient, as resulting number of  command calls is much smaller. In my case, I see 6-12 times better performance when using `args` then when using `-exec` solution with growing number of files is the efficiency growing.
Answer: That happens because your wildcard expression (*.jpg) exceeds the command line argument length limit when expanded (probably because you have lots of .jpg files under /home/ftpuser/public_html/ftparea).
There are several ways for circumventing that limitation, like using find or xargs. Have a look at this article for more details on how to do that.
Comment: +1 for the good external resource on subject.
Answer: As GoldPseudo commented, there is a limit to how many arguments you can pass to a process you're spawning.  See his answer for a good description of that parameter.
You can avoid the problem by either not passing the process too many arguments or by reducing the number of arguments you're passing.
A for loop in the shell, find, and ls, grep, and a while loop all do the same thing in this situation --
for file in /path/to/directory/*.jpg ;
do
  rm "$file"
done

and
find /path/to/directory/ -name '*.jpg' -exec rm  {} \;

and
ls /path/to/directory/ |
  grep "\.jpg$" |
  while
    read file
  do
    rm "$file"
  done

all have one program that reads the directory (the shell itself, find, and ls) and a different program that actually takes one argument per execution and iterates through the whole list of commands.
Now, this will be slow because the rm needs to be forked and execed for each file that matches the *.jpg pattern.
This is where xargs comes into play.  xargs takes standard input and for every N (for freebsd it is by default 5000) lines, it spawns one program with N arguments.  xargs is an optimization of the above loops because you only need to fork 1/N programs to iterate over the whole set of files that read arguments from the command line.
Answer: There is a maximum number of arguments that can be specified to a program, bash expands *.jpg to a lot of arguments to cp. You can solve it by using find, xargs or rsync etc.
Have a look here about xargs and find
https://stackoverflow.com/questions/143171/how-can-i-use-xargs-to-copy-files-that-have-spaces-and-quotes-in-their-names
Answer: Using the + option to find -exec will greatly speed up the operation.
find  /home/ftpuser/public_html/ftparea/ -name "*jpg" -exec cp -uf -t /your/destination "{}" +

The + option requires {} to be the last argument so using the -t /your/destination (or --target-directory=/your/destination) option to cp makes it work.
From man find:

-exec command {} +

          This  variant  of the -exec action runs the specified command on
          the selected files, but the command line is built  by  appending
          each  selected file name at the end; the total number of invoca‐
          tions of the command will  be  much  less  than  the  number  of
          matched  files.   The command line is built in much the same way
          that xargs builds its command lines.  Only one instance of  '{}'
          is  allowed  within the command.  The command is executed in the
          starting directory.

Edit: rearranged arguments to cp
Comment: I am getting find: missing argument to `-exec'

/home/ftpuser1/public_html/ftparea/ -name '*jpg' -exec cp -uf "{}" /home/ftpuser2/public_html/ftparea/ +
Comment: I rearranged the arguments to `cp` to fix that error.
Answer: The '*' glob is expanding to too many filenames.  Use find /home/ftpuser/public_html -name '*.jpg' instead.
Comment: Find and echo * result in the same output -- the key here is using xargs not just passing all 1 billion command line arguments to the command the shell's trying to fork.
Comment: echo * will fail if there are too many files, but find will succeed.  Also, using find -exec with + is equivalent to using xargs.  (Not all find support +, though)
Answer: It sounds like you have too many *.jpg files in that directory to put them all on the command line at once. You could try:
find /home/ftpuser/public_html/ftparea1 -name '*.jpg' | xargs -I {} cp -uf {} /home/ftpuser/public_html/ftparea2/

You may need to check man xargs for your implementation to see whether the -I switch is correct for your system.
Actually, are you really intending to copy those files to the same location where they already are?
Comment: apologies these are two different directories should be ftpuser1 and ftpuser2
Comment: Just tried this:
ls /home/ftpuser1/public_html/ftparea/*.jpg | xargs -I {} cp -uf {} /home/ftpuser2/public_html/ftparea/

Still got -bash: /bin/ls: Argument list too long
Comment: Oh, you're quite right, of course `ls` will have the same problem! I've changed to `find` which won't.
Answer: Go to folder
cd /home/ftpuser1/public_html/

and execute the following:
cp -R ftparea/ /home/ftpuser2/public_html/

In this way if the folder 'ftparea' has subfolders, this might be a negative effect if you want only the '*.jpg' files from it, but if there aren't any subfolders, this approach will be definitely much more faster than using find and xargs


Analysis to identify groups of occupations with similar skill demand from job postings?

Question: Was told to post this here so hope it's the right place!
I am using a very large dataset of job postings, which for each posting has a unique posting ID, the job posting occupation, and a row for each skill requested in each job posting.
The dataset looks a bit like this:

posting_id
occ_code
occname
skillname

1
1
data scientist
analysis

1
1
data scientist
python

2
2
lecturer
teaching

2
2
lecturer
economics

3
3
biologist
research

3
3
biologist
biology

4
1
data scientist
research

4
1
data scientist
R

I'd like to perform analysis (in R) to identify "related" occupations by how similar their overall skill demand is in job postings. E.g. using a sample of 1000 postings for data scientists and 1000 for financial analysts, if many of the postings requested the same skills they could be considered closely related occupations.
There are hundreds of different occupations in the dataset, but out of those I'm interested in identifying occupations with similar kind of "skill profile" to 25 specific occupations I have selected.
Haven't done anything like this before so I'm struggling to come up with what type of analysis would be appropriate to achieve this. Would greatly appreciate any advice!
Comment: There is a working paper that uses BERT to do [that.](https://hai.stanford.edu/news/words-matter-text-online-job-postings-can-predict-salaries)
Comment: @dimitriy This is a promotional piece that Stanford wrote for one of its scientist. As universities do nowadays.
The link "Indeed, using machine learning, Bana recently showed that ..." doesn't even open anymore.
Since the only thing that seems to have been shown about these large language models is that they are biased against minorities of various kinds, it might be a good idea to not promote this yourself?
Comment: Here is [the link to the paper itself](https://static1.squarespace.com/static/573f69a2cf80a1adb090ba64/t/63b7aaefd09bf6373f4c7e61/1672981234385/work2vec_salaries.pdf).
Answer: Think of skill names like words, job postings like sentences, and occupations like books.
Two books are similar if they use a lot of the same words, perhaps taking into account their frequency.  Similarly, two occupations are similar if the job postings for those occupations mention the same skills.
Roughly, I would:

Count how many times a skill is mentioned in an occupation.  You could merge all the postings together here.
Create a occupation-skill matrix.  Rows are occupations, skills are columns, and the entry in position i,j is the count of times skill j is mentioned for occupation i.
Perform any method of similarity you like.  I think transfgorming the counts using TF-IDF and then doing something as simple as a cosine similarity would work perfectly fine.

There is no "right" approach here because "similar" is not well defined.  So you have to make some choices about how to represent the skills within occupations, and some decisions about how to define "similar" in that representation.  I've mentioned but one way, but you could for example just do 1s and 0s for if the skill is mentioned in any of the job postings for that occupation and then compute a Jaccard index.
Comment: Thanks for the detailed reply and I really like the idea. I wasn't familiar with TF-IDF and it looks good - one issue though is that because there are so many job postings (millions), many of the skills are mentioned in every occupation's job postings at least once. From my (limited) understanding of TF-IDF, does this mean I can't use it? It seems like even if a skill is mentioned 10,000 times in postings for one occupation and one single time in every other occupation, this would ruin it due to how the IDF calculation works.
Comment: @Dandae No this should be fine.  TF-IDF will down weight the skill if it appears in a lot of postings (that is, lots of postings for different roles).  This is the IDF part of TFIDF.
Comment: If they just appeared in lots of postings it would be fine, but due to the high number of postings in the dataset, for many of the skills they appear in at least one posting for every occupation, which makes the IDF value 0 (and therefore TF-IDF value also 0) for a large proportion of the skills.
Comment: Just to update on this, I've decided to use the IDF formula here: https://lucene.apache.org/core/5_1_0/core/org/apache/lucene/search/similarities/TFIDFSimilarity.html

to ensure the calculate IDF > 0


Updating fontsize with highcharts using zoomtype

Question: I have a column chart in Highcharts with a big number of columns so the columns are very small.
That's fine but I want to do zoom.
So I used zoomtype: 'x' and it work well.
The problem is that I want to make the font bigger on the xAxis when they are selected.
I tried by doing this:
chart: {
            type: 'column',
            zoomType: 'x',
            events: {
                redraw: function(event) {
                    if(this.xAxis[0].tickPositions.length>80){
                        this.xAxis[0].options.labels.style.fontSize = 1;
                    }else{
                        this.xAxis[0].options.labels.style.fontSize = 20;
                        console.log(this.xAxis[0].options.labels.style.fontSize);
                    }

                }

            }
        }

When I check the console the value of this.xAxis[0].options.labels.style.fontSize is updated to 20.
This code works only when I press the Reset zoom button.
So my question is how can I update the chart when the event is triggered so it takes the same effects as if I use the Reset zoom button?
Or how can I make changes in the font when I make zoom and when reseting the zoom?
Answer: You can catch afterSetExtremes event and then axis.update() with new styles for bales.
events:{
            afterSetExtremes:function(){
                this.update({
                    labels:{
                        style:{
                            fontSize:20
                        }
                    }
                });
            }
 }

Example: http://jsfiddle.net/m180dxsu/
Comment: It works perfect!! I lose a lot of time trying other stuff that did not work. Thank you very much.


Why does k-NN (k=1 and k=5) does not use the nearest points?

Question: I was looking at this picture and I do not understand why that one point (the one I drew an arrow at) gets classified with K = 1 and K = 5 in a blue area. For K = 1 the nearest neighbor should be the green one, definitely not a blue one and for K = 5 I can see 3 green points, 1 red point and maybe there's 1 blue point near. But in the end, that blue point should be green as well as far as I understood that algorithm. Can someone explain me why that point is not in the green area for K = 1 and K = 5?
Answer: It looks like the graphs are plotting the training data, and classification regions. The blue point is blue because it is labeled blue in the training data. The classification regions are created by visiting each pixel, and coloring it the color of the majority vote of the $k$ nearest training points to that pixel.
Answer: These points are the training set. So, for $K=1$, the closest point to the lower left blue point is itself. That's why you see a weird red region nearby. Similar situation for $K=5$, the closest points are two blues, two green and one red. It seems in case of equality blue has been chosen for that specific node.
Answer: When $k = 1$, you are computing a Voronoi diagram.  So the partitions between classes will be made of line segments perpendicular to the two nearest points of differing colors.  The point you indicate and the green point at about $(4.9, 2.4)$ establish the blue/green boundary to the right of your indicated point.
When $k = 5$, consider the cluster of one blue, one red, and three green points in $[4.5, 5.1] \times [2.3, 2.5]$.  This is a set of $k = 5$ points, three of which are green.  At the called out point, the distance to the blue member at $(4.4, 2.9)$ and the green member at $(5.1, 2.5)$ are (about) the same, so we should expect a transition from green dominance to a green-blue tie moving to the left somewhere near the called out point.  The coloring scheme used appears to favor blue in such a tie.


CFEngine 3.5 Oracle JDK promise

Question: CFEngine 3 newbie here.
Am trying to get Oracle JDK installed on an Ubuntu system, how should I script it in CFEngine?
I can do something like this in shell by using PPA provided by webupd8team:
add-apt-repository ppa:webupd8team/java
apt-get update

echo "Installing JDK 7..."
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
apt-get install -y oracle-java7-installer

Am totally lost doing this in CFEngine. So far I have:
body common control {
    inputs => { "$(sys.libdir)/stdlib.cf" };
    bundlesequence => { "manage_properties",
                        "manage_jdk"};
}

bundle agent manage_properties {
    vars:
        "prop_pkgs" slist => {"python-software-properties", "software-properties-common"};
        "cmds"      slist => {  "/usr/bin/add-apt-repository ppa:webupd8team/java",
                                "/bin/echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections",
                                "/bin/echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections",
                                "/usr/bin/apt-get update" };

    methods:
        "$(prop_pkgs)"
            handle => "manage_properties",
            comment => "Make sure required properties packages are installed",
            usebundle => package_latest("$(prop_pkgs)");

    commands:
        "$(cmds)"
            comment => "Firing preinstall commands for JDK";
}

bundle agent manage_jdk {
    methods:
        "JDK"
            handle => "manage_jdk",
            comment => "Make sure Java is installed",
            usebundle => package_latest("oracle-java7-installer");
}

But the promise fails with following error:
2014-06-30T14:11:18+0000    error: /default/manage_jdk/methods/'JDK'/default/package_latest/packages/'oracle-java7-installer'[0]: Finished command related to promiser 'oracle-java7-installer' -- an error occurred, returned 100
2014-06-30T14:11:18+0000    error: /default/manage_jdk/methods/'JDK'/default/package_latest/packages/'oracle-java7-installer'[0]: Bulk package schedule execution failed somewhere - unknown outcome for 'oracle-java7-installer'

Would appreciate any pointer. Thanks
Answer: One thing that I see in your policy is that you are running some commands that require a shell (your piped commands) and your commands promise is not being contained within any shell.

commands:
  "/bin/echo 'Hello World' | grep Hello"
    contain => in_shell;

Also, it seems that you are taking a very imperative view with your pre-commands. CFEngine typically runs policy once every 5 minutes. I would focus more on performing the operations necessary when necessary and try to focus on the state instead of action.
For example your running apt-add-repository unconditionally. Consider under what conditions you actually need to execute the command.

CFEngine 3.5 Oracle JDK promise


Relatório em PHP com quebra de seção

Question: Tenho uma consulta em MySQL que me retorna várias linhas de resumos de vendas agrupados por vendedor. Cada vendedor é de uma cidade. Como insiro um sub-total ao final de cada cidade? Uso PDO para abstração.
A instrução é essa:
SELECT rpaautonomos.autonomo, MASK(rpaautonomos.cpf, '###.###.###-##') AS cpf, MASK(rpaautonomos.inss, '###.###.####-#') AS inss, DATE_FORMAT (rpaautonomos.nascimento,'%d/%m/%Y') AS nascimento, CONCAT('R$ ', FORMAT((SUM(rparecibos.valor) + SUM(rparetencoes.retido)), 2, 'de_DE')) AS bruto_mensal, CONCAT('R$ ', FORMAT(SUM(rparetencoes.inss), 2, 'de_DE')) AS inss_mensal, CONCAT('R$ ', FORMAT(SUM(rparetencoes.irf), 2, 'de_DE')) AS irf_mensal, CONCAT('R$ ', FORMAT(SUM(rparetencoes.iss), 2, 'de_DE')) AS iss_mensal, CONCAT('R$ ', FORMAT(SUM(rparetencoes.retido), 2, 'de_DE')) AS retido_mensal, CONCAT('R$ ', FORMAT(SUM(rparecibos.valor), 2, 'de_DE')) AS valor_mensal FROM rparecibos INNER JOIN rpaautonomos ON rparecibos.cpf = rpaautonomos.cpf INNER JOIN rparetencoes ON rparecibos.chave = rparetencoes.chave WHERE MONTH(rparecibos.emissao) = MONTH(NOW()) GROUP BY rpaautonomos.autonomo ORDER BY rpaautonomos.autonomo ASC

Comment: Quer denunciar um comportamento injusto adotado pelos usuários do site use o canal de comunicação competente que é [meta] onde são discutidos o funcionamento e as políticas do Stack Overflow em Português em vez de discutir o programação em si, seja franco e abra uma discussão expondo o problema apontando os responsáveis e as provas. Não use o campo de comentários para ventilar acusações genérica, esse só deve ser usado para realizar orientações e esclarecimentos a respeito das publicações.
Comment: O que?? Poderia esclarecer a pergunta.
Comment: Precisava de inserir um subtotal ao final de cada autônomo no relatório, e estava tentando fazer via SQL mas achei uma solução pelo PHP.
Answer: Fiz em PHP da forma abaixo e deu certo...

if ($relatorio) {
    foreach ($relatorio as $row) {
        [...]
        $bruto_mensal += $row["bruto_mensal"];
        $inss_mensal += $row["inss_mensal"];
    }
    $tg_bruto_mensal = number_format($bruto_mensal, 2, ",", ".");
    $tg_inss_mensal = number_format($inss_mensal, 2, ",", ".");
}

Relatório em PHP com quebra de seção


Accessing the value of an int which has been modified in another

Question: Apologizes if this is an obvious question. I have a VC A and a VC B(which is a subclass of A). In A's .m I have a int Counter called currentQuestion. If the user enters the wrong answer VC A goes to VC B. In B i want to access the current value of currentQuestion in order to place the correct image in leftImageViewer.  It does seem to recognise currentQuestion as a variable already instantiated but does not show the correct value.
leftImageViewer.image = [UIImage imageNamed:left[currentQuestion]];

Comment: Can you post the code of how you go to VC B ?
Comment: `- (IBAction)SelectC:(id)sender {

    if ([self.correctAns isEqualToString:@"C"]) {

    [self showNextQuestion];
    }
    else{
        [self performSegueWithIdentifier:@"segueToB" sender:nil];
    }
}`
Comment: I think you could use the sender parameter in your 'perform segueWithIdentifier:sender: When you pass self as sender you can access the instance variables of VC A in VC B using sender.variable
Answer: You will have to pass the value of currentQuestion to VCB, since VCB is creating entirely new instances of all the instance variables (or that is what generally happens, hard to tell with outseeing the code):
// an example of how to create 'VCB', this is NOT in 'VCB.m'
VCB *vcb = [[VCB alloc] init];
[vcb setCurrentQuestion:[self currentQuestion]];
// present 'vcb' how you are doing so now

Of course, this is assuming you have a property @property int currentQuestion.
More generally, you would want look at the concepts of inheritance and polymorphism to have a better understanding of what is happening.
UPDATE:
Your VCA should look like:
@interface VCA : UIViewController
    // ...
@property int currentQuestion; // this will allow 'currentQuestion' to be accessible
    // ...
@end

To understand why and how this will work, I encourage you to get a better understanding of how inheritance works. It is a fundamental concept in object oriented programming.
Comment: This part would go into the .m of VCB?  Yes I have declared `@interface AVC : ViewController{
    int currentQuestion;
    }`
Comment: This should go in the place where you initialize VC B. As @Mike D has written, when creating a new instance of VC B it won't know the value of the currentQuestion variable regardless it is a subclass of VC A.
Comment: @Sfocker See my update. But there is an important concept involved here that is used in all higher level languages, frameworks, and SDKs.
Comment: Mike. Thanks for the update. I do think I have a firm grasp of what your saying to an extent. A is the rootclass, B in inheriting from A. Everything declared in A is available to use in B, but its just another instance of currentQuestion. Its not the actual value of currentQuestion in AVC's. Have I this correct?
Comment: @Sfocker That is correct. When you create an instance of `VCB`, you are getting a new instance of `currentQuestion`, same with all the other instance variables and properties declared in VCA.
Comment: Okay. I do not understand where this code goes
`VCB *vcb = [[VCB alloc] init];
[vcb setCurrentQuestion:[self currentQuestion]];`

Just before I call the VCB segue in the VCA?
Comment: That doesn't seem to be working for Me. Should I have VCB imported into VCA or anything like that?
Comment: @Sfocker I think with that, it might be easier at this to declare a protocol that both view conttrollers can adopt and remove the inheritance component. I'll update in afew minutes.
Comment: http://stackoverflow.com/questions/15531352/accessing-the-value-of-a-variable-in-the-root-class-from-a-subclass @MikeD here is a more comprehensive look at my problem it may help.Thankyou


Let $X_1, ... , X_5$ be a random sample from $p(x;\theta)=(1-\theta)^{x-1}\theta$. Find the UMPT size $\alpha = 0.1$.

Question: Let $X_1, \ldots , X_5$ be a random sample from $p(x;\theta)=(1-\theta)^{x-1} \theta$, for $x=1,2,3,\ldots$. Consider $H_0:\theta \geq 0.7\text{ vs. } H_1:\theta<0.7$. Find the UMPT size $\alpha = 0.1$.
My try: let $$H_0^{'}:\theta_0 = 0.7\text{ vs. } H_1^{'}:\theta=\theta_1 \quad(\theta_1<0.7)$$
Now, using the NP Lemma $$\frac{L(\theta_1)}{L(\theta_0)} = \frac{(1-\theta_0)\theta_1^n(1-\theta_1)^{\sum ^5_{i=1}x_i}}{(1-\theta_1)\theta_0^n(1-\theta_0)^{\sum ^5_{i=1}x_i}}\geq k$$
Then I end up with $$\sum ^5_{i=1}x_i\geq c$$
Then $$\Psi^*(x)=
\begin{cases}
1&\sum ^5_{i=1}x_i\geq c\\
0&\sum ^5_{i=1}x_i< c.
\end{cases}$$
In order to find alpha, I need to know the probability distribution of $\sum ^5_{i=1}x_i$ but I'm not sure how to do this or if my method is correct. Any suggestions would be great!
Comment: Looks good! For the next step, do you recognize the probability distribution and know its generalization? Or you know how to use moment generating functions?
Comment: you should look into the negative binomial and the geometric distributions
Comment: I don't recognize it. I know that it must be a discrete distribution (maybe binomial). Any hints?
Answer: Your application of the Neyman-Pearson lemma looks good. To complete the problem, you need to identify the distribution of $Y = X_1 + \cdots+ X_5$. Notice that $X_i$ counts the number of Bernoulli trials until a success, so that $Y$ counts the number of trials until you get $5$ successes. To get $P(Y=y)$, we simply need to count:

Observe that the $y$-th Bernoulli trial must be a success
In the previous $y-1$ trials, we must have observed $4$ successes and $y-5$ failures; there are ${y-1 \choose 4}$ ways in which these trials can happen

Hence, for $y \geq 5$,
$$P(Y=y) = {y-1 \choose 4} \theta^5 (1-\theta)^{y-5} $$
This distribution is sometimes called the negative binomial distribution.


A polynomial is divisible with another one

Question: For what $m$ and $n$ is the polynomial $2X^{19}+X^{13}+mX^{11}+X^8+2X^6+nX^2+2$ divisible by $X^4+X^3+X^2+X+1$.
I tried to find the real solutions for g but couldn't
Answer: HINT:
$$x^5-1=(x-1)(x^4+x^3+x^2+x+1)=0$$
$$\implies x^{19}=x^4,x^{13}=x^3$$
Answer: Note that $x^5-1=(x-1)(x^4+x^3+x^2+x+1)$
\begin{align}
&\;2x^{19}+x^{13}+mx^{11}+x^8+2x^6+nx^2+2\\
=&\;2x^4(x^5-1+1)^3+(x^3+mx)(x^5-1+1)^2+(x^3+2x)(x^5-1+1)+nx^2+2\\
=&\;2x^4[(x^5-1)^3+3(x^5-1)^2+3(x^5-1)+1]\\
&\quad+(x^3+mx)[(x^5-1)^2+(x^5-1)+1]+(x^3+2x)[(x^5-1)+1]+nx^2+2\\
=&\;P(x)(x^5-1)+2x^4+x^3+mx+x^3+2x+nx^2+2
\end{align}
for some polynomial $P(x)$.
$2x^{19}+x^{13}+mx^{11}+x^8+2x^6+nx^2+2$ is divisible by $x^4+x^3+x^2+x+1$ if and only if $2x^4+x^3+mx+x^3+2x+nx^2+2$ is divisible by $x^4+x^3+x^2+x+1$.
\begin{align}
&\;2x^4+x^3+mx+x^3+2x+nx^2+2\\
=&\;2x^4+2x^3+nx^2+(m+2)x+2
\end{align}
It is obvious that $m=0$ and $n=2$.


When to stop training of neural network when validation loss is still decreasing but gap with training loss is increasing?

Question: During training of CNNs, I often come across this case for training and validation loss :
X axis is epochs, Y axis is cross entropy loss.
I would like to keep the "best model", meaning the one which generalizes the best (I wish to use it for fine-tuning on another dataset).
So up until now, I wass keeping the model at the "green line" point : the one with the lowest validation loss. However, I'm concerned because before that point, the gap between training loss and validation loss has increased, which indicates overfitting. So should I rather be keeping the model at the "red line", before overfitting gets too much out of hand ?
Comment: A gap between training and testing loss does not indicate overfitting. This is a very common fallacy.
Comment: Could you please elaborate @MatthewDrury ? I know a small gap is nothing to worry about, but what does a widening gap like so indicate ?
Comment: Sure, will do after i get off the bus!
Answer: As long as your validation loss is continuing to decrease, your model is continuing to perform better in a generalized setting.
A growing gap between training and validation performance does mean that your model is treating more and more of the noise in your training set as real signal. However, the fact that your validation loss is decreasing means that the model is taking even more advantage of true signal. In some sense, it's gaining more generalizability than it's losing.
I would agree with your first instincts, and choose the model at the iteration indicated with the green line.


Cauchy sequences and complete spaces

Question: I'm trying to fully understand the complete metric spaces so I came up with this reasoning: every metric space X can be extended to a complete metric space Y and every Cauchy sequence in X is still Cauchy in Y, but it's also convergent in Y. This means that Cauchy sequences are always convergent, but not always they converge inside the space.
Now, the closure of a set X is the set that contains all limits of all convergent sequences of elements of X, so it should also contain all limits of all Cauchy sequences.
But this is the definition of a complete metric space, so now I'm lost.
Is it true that every closed metric space is complete? I know it's true in Euclidean spaces, but I thought it wasn't true in general.
Edit: I just realised that we know that every closed subset of a complete metric space is complete, but since every metric space can be extended to a complete space, this means that every closed space is complete, right?
So is completeness less strong than closedness?
Comment: I'll leave the answer to an analyst, but a quick comment: 'Cauchy sequences are always convergent' - no, most people would take issue with this statement, although your overall logic in that sentence is sound. If the sequence doesn't converge within the space in question, don't call it convergent. Welcome to MSE Emanuele, nice opening Q!
Answer: Every metric space is a closed subset of itself, and therefore, since there are non-complete metric spaces, the sentence "every closed metric space is complete" is false.
But, yes, if $X$ is a metric space, you can extend it to a complete metric space $Y$ (its completion), and the closure of $X$ in $Y$ is the whole $Y$.
Comment: Yes. The space $Y$ is a metric space with respect to some metric $d$, and its topology is obtained from that metric.
Comment: Dear Jose, thank you indeed for this enlightening example.  Intuitively, I do believe that the closure of X is Y. On the other hand, I wish to enquire: closure -- with respect to what topology? Just any topology? Or the standard topology induced by the distance d ?
Comment: @Michael_1812 The set $X$ is a subset of the metric space $Y$. I am talking about the closure of $X$ in $Y$.
Comment: The closure of a set is the union of the set with all its limit points. A point p is a limit point of X iff every neighbourhood of p contains at least one point of X different from p. By saying `neighbourhood', we automatically imply the existence of some topology. Please correct me if I am wrong. [I suspect that you are implying the standard topology defined by open balls in the sense of the distance d of the metric space. Is that right?]
Comment: This is what I thought. Thank you very much!
Answer:
When you say : "so it should contain all limits of Cauchy sequences", it seems that you are concluding that the set of convergent sequences is the same as the set of Cauchy sequences. This happens when $X$ is complete, by definition.

In fact, a way to define the completion of $(X,d)$ is precisely to consider an equivalence relation on the set of all Cauchy sequences of $X$, where $(a_n)$ and $(b_n)$ are equivalent iff $\lim d(a_n,b_n)=0$. This will "fill up the holes in $X$". A well known result illustrates this idea : a metric space $(X,d)$ is complete iff any decreasing sequence of nonempty closed sets $F_1\supset ...\supset F_n\supset ...$ with $diam(F_n)\rightarrow 0$ is such that $\bigcap F_n$ is non empty (in fact, a singleton).

If $F\subseteq X$ is a closed subset of a complete metric space, consider any Cauchy sequence $(x_n)$ in $F$. Since the distance is the same in both spaces, the sequence is also Cauchy in $X$, where it converges to some $x$ due to completeness of $X$. But $F$ is closed, so $x\in F$.
Comment: In item (3) of this proof, the closedness is understood in the sense of the so-called *standard topology*, the one induced by the distance $d$ and its open balls.

Cauchy sequences and complete spaces


SQL populate with autoincrement, but reset on foreign key changed

Question:
Hi, I have table like this and I have to populate column Test with autoincrement, but autoincrement must reset to 1 each time DAId foreign key is changes.
I need sql script to execute in .net core migration.
This should be final resault.
Comment: Tag your question with the database you are using.
Answer: You seem to want row_number():
select id, daid,
       row_number() over (partition by daid order by id) as test
from t;

If you want to update the value, then the syntax depends on the database.  The mention of ".net" suggests SQL Server.  If so, that has a very convenient ability called updatable CTEs:
with toupdate as (
      select t.*,
           row_number() over (partition by daid order by id) as new_test
      from t
     )
update toupdate
    set test = new_test;


Error when importing the configuration

Question: We have several sites running with Drupal.
On my local machine I run the test versions of each site in the Docker container to add new features or test new ones.
When switching between pages I do the following.
Shut down the container of page-A.
Change to the directory of page-B, start the container.
Then execute the following commands in the terminal in the container:
composer clearcache
composer install
drush sql-drop --yes;
drush sqlc < page-B_init.sql
drush updb
drush cim

When running drush cim, the following error message appears:
 [error]  Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization.
Entity type mismatch on rename.  not equal to configurable_language for existing configuration system.site and staged configuration language.entity.en.
Rename operation for simple configuration. Existing configuration system.site and staged configuration language.entity.en. in Drupal\Core\Config\ConfigImporter->validate() (line 755 of /var/www/html/docroot/core/lib/Drupal/Core/Config/ConfigImporter.php).

In ConfigImportCommands.php line 261:

  The import failed due to the following reasons:
  Entity type mismatch on rename.  not equal to configurable_language for existing configuration system.site and staged configuration language.entity.en.
  Rename operation for simple configuration. Existing configuration system.site and staged configuration language.entity.en.

I suspect the problem is with the UUID, which I have in the files:
environments/_default/config/sync/system.site.yml
environments/_default/config/sync/language.entity.en.yml

adapted.
But I don't know any further.
Does anyone have an idea where the error lies?
Use Drupal 8.9.13
Answer: This might not be the best way, but I had this same issue today. I ended up renaming language.entity.en.yml to include .OLD at the end of the filename for a backup, then I re-ran drush cim. After that it accepted my system.site.yml file. Then I took a look at the language.entity.en.yml file and for some reason it had the exact same UUID as the system.site file. I suspect the import is confused about which file is which because they both had the same UUID.

Error when importing the configuration


Is there a way to use jQuery?

Question: I heard Drupal 10 will no longer support jQuery out-of-the-box.
Is there a way to use jQuery in Drupal 10?
My guess would be that adding jQuery to a module's composer.json file would allow jQuery code to continue to function. I know this is not best practice, but large sites might need additional time to transition away from jQuery.
Comment: I think jQuery UI is gone in Drupal 10.
Answer: jQuery is still included in Drupal 10.1core.
If it would be removed in the future you would actually add a libraries file: https://www.drupal.org/docs/creating-custom-modules/adding-assets-css-js-to-a-drupal-module-via-librariesyml
I would fully expect a contributor would share such a module.
Comment: It wasn't removed https://git.drupalcode.org/project/drupal/-/blob/10.1.x/core/core.libraries.yml#L755
Comment: I did a search for jQuery for Drupal 10 but did not find any modules yet. Do you know of any?

Is there a way to use jQuery?


Maximum of a Function Bounded by Average of Integral and Integral of Derivative

Question:
Suppose $f$ is continuous and that $f$ is $C^1$. Prove that $$\max_{x\in[a, b]}|f(x)|\;\leq\; \frac{1}{b-a}\Big|\int_a^b f(x)dx\Big| \,+\, \int_a^b |f'(x)|dx.$$
(Hint: how are the maximum of $f(x)$ and its average related by the fundamental theorem of calculus?)

Could somebody provide an example proof?
Comment: @bjorn93 in the proof user284331 gave, I saw he wrote $|f(x)|$ - how can we show this for max$|f(x)|?$
Answer: Observe that $$\int_{a}^{b} |f'| \geq \max_{s,t \in [a,b]} \left|\int_{t}^{s} f'\right| =\max_{s,t \in [a,b]} |f(s)-f(t)| \geq \max_{s,t \in [a,b]} |f(s)|-|f(t)| = \max_{s \in [a,b]} |f(s)| - \min_{s \in [a,b]} |f(s)|$$
and $$\frac{1}{b-a} \left|\int_{a}^{b} f\right| = |f(c)|$$ for some $c \in [a,b]$ by the mean value theorem.
The result follows from the fact that $|f(c)| \geq \min_{s \in [a,b]} |f(s)|$.
Comment: @TimBrady is because of [triangular inequality](https://en.wikipedia.org/wiki/Triangle_inequality): $|x + y| \leq |x|+|y|$, in its integral form is equivalent to $|\int f dt| \leq \int |f| dt$... so $\sup | \int_s^t f' | \leq \sup \int_s^t |f'|$ and since you are adding now only positive values, given that $[s, t] \subset [a, b]$ it follows that $\sup \int_s^t |f'| \leq \sup \int_a^b |f'|$... with the answer already given the full question is solved.


Suppose f and g are nonnegative measurable functions from S to $[0,\infty]$ . Show that $\{s \in S \mid f(s)\gt g(s)\}$ is measurable

Question:
Suppose $f$ and $g$ are nonnegative measurable functions from $S$ to $[0, \infty]$. Show that $\{s \in S \mid f(s)\gt g(s)\}$ is measurable (wrt the sigma algebra on $S$).

There is an answer here Let $f,g$ be measurable functions, show that $\{s\in S: f(s) = g(s)\}\in \mathcal{A}$.
If someone could elaborate on the reasoning in the solution (I have almost no feel for these objects) It would be helpful.  Thanks in advance.
Edit: Also, my professor prefers me to relate to the ray sets $\{s\in S\mid f(s)\leq t\}$ and not arbitrary Borel sets, as is done in the solution posted.
Answer: $f(s) >g (s)$ iff there is a rational number $q$ such that $f(s)>q>g(s)$. So we can write $\{s:f(s)>g(s)\}$ as $\cup_{q \in \mathbb Q} (\{s: f(s) \leq q\})^{c} \cap \{s:g(s)<q\}$. To finish the proof note that $\{s:g(s)<q\} =\cup_n \{s:g(s) \leq q-\frac 1 n\}$.


How to add two extra buttons in a form to do extra actions with form data

Question: I have a simple custom form with 3 submit buttons - one that calls the default hook_form_submit and generates a table. The submit as the rebuild as TRUE:
<code>$form_state['rebuild'] = TRUE;
</code>
that shows the complete form with the 3 buttons and the tables.
I need the 2 extra buttons to call different functions but I need inputs from the form itself or the table array.
At the moment, with the code I have, I can't access the form data and also, the tables created by the main submit disappear when I click the 2 extra buttons.
My code:
<code>function MYMOUDLE_form($form, &$form_state) {
    $form['container']['submit'] = array(
        '#type' => 'submit',
        '#value' => t("Submit Form"),
    );

    $form['container']['export_1'] = array(
        '#type' => 'submit',
        '#value' => t("Export - 1"),
        '#submit' => array('MYMOUDLE_export_1'),
    );

    $form['container']['export_2'] = array(
        '#type' => 'submit',
        '#value' => t("Export - 2"),
        '#submit' => array('MYMOUDLE_export_2'),
    );

    return $form;
}

function MYMOUDLE_form_submit($form, &$form_state) {
    # do my stuff - generate tables
}

function MYMOUDLE_export_1($form, $form_values) {
    dpm($form_values);
    $someData1 = MYMODULE_handleFormData1($formValue1, $formValue2, $formValue3);
    drupal_set_message('Action for export 1 was done successfully.');
}

function MYMOUDLE_export_2($form, $form_values) {
    dpm($form_values);
    $someData2 = MYMODULE_handleFormData2($formValue1, $formValue2, $formValue3);
    drupal_set_message('Action for export 2 was done successfully.');
}
</code>
Comment: You probably need to rebuild the form, not redirect. See https://drupal.stackexchange.com/questions/224917/send-form-result-back-to-twig
Comment: Sorry. I have redirect in my submit. $form_state['rebuild'] = TRUE;
Comment: OK, if you rebuild the form you should see the form data when rebuilding the form. By the way you can check in $form_state the triggering element so that you know which button was pressed before rebuilding.
Comment: I added $form_state['rebuild'] = TRUE; to the MYMOUDLE_export_1 and MYMOUDLE_export_2 and changed the arguments to "$form, &$form_state". That solved it. I now have access to the form_state and the form is completely rebuilt.
Answer: Rather than write submit function for each button use $form_state['triggering_element']. This will provide you the which button is clicked with form data in default hook_form_submit


Can't find solution Failed to create directory 'activemq-data\localhost\KahaDB'

Question: I am trying to integrate ActiveMQ with Tomcat on this tutorial
How to embed ActiveMQ in Tomcat
When I start the server I am receiving Failed to create directory 'activemq-data\localhost\KahaDB'.
How can it be solved?
Also I don't know where to put parameters
<code>-Dwebconsole.type=properties
</code>
-Dwebconsole.jms.url=tcp://localhost:61616
-Dwebconsole.jmx.url=service:jmx:rmi:///jndi/rmi://localhost:1099/Jmxrmi
Log:
java.lang.RuntimeException: java.io.IOException: Failed to create directory 'activemq-data\localhost\KahaDB'
    at org.apache.activemq.store.kahadb.KahaDBStore.size(KahaDBStore.java:1208)
    at org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter.size(KahaDBPersistenceAdapter.java:217)
    at org.apache.activemq.usage.StoreUsage.retrieveUsage(StoreUsage.java:56)
    at org.apache.activemq.usage.Usage.caclPercentUsage(Usage.java:283)
    at org.apache.activemq.usage.Usage.onLimitChange(Usage.java:188)
    at org.apache.activemq.usage.Usage.setLimit(Usage.java:172)
    at org.apache.activemq.broker.BrokerService.getSystemUsage(BrokerService.java:1156)
    at org.apache.activemq.broker.BrokerService.checkMemorySystemUsageLimits(BrokerService.java:2136)
    at org.apache.activemq.broker.BrokerService.start(BrokerService.java:599)
    at info.octera.utils.LoadActiveMQ.init(LoadActiveMQ.java:32)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4921)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5231)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1439)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1429)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1439)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1429)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:655)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: java.io.IOException: Failed to create directory 'activemq-data\localhost\KahaDB'
    at org.apache.activemq.util.IOHelper.mkdirs(IOHelper.java:331)
    at org.apache.activemq.store.kahadb.MessageDatabase.createPageFile(MessageDatabase.java:3118)
    at org.apache.activemq.store.kahadb.MessageDatabase.getPageFile(MessageDatabase.java:3283)
    at org.apache.activemq.store.kahadb.KahaDBStore.size(KahaDBStore.java:1206)
    ... 43 more
Comment: you need to put these parameters in the tomcat startup script $CATALINA_HOME/bin/catalina.sh or catalina.bat  http://stackoverflow.com/a/12407817/6506229
Comment: can you post error logs
Comment: Today I moved eclipse and Tomcat into disk D and project is working. But how can I provide rights Tomcat to read and right on disk C in the folder C:\Program Files \eclipse\activemq-data\localhost\KahaDB?
Comment: https://msdn.microsoft.com/en-us/library/bb727008.aspx
Answer: on windows, I needed to specify the directory with a driver letter infront to get this working, ex
<code><amq:broker useJmx="false" persistent="true" schedulerSupport="true" dataDirectory="c:\active-mq"> ....
</code>


try/catch no switch criando loop infinito na execução

Question: Estou querendo também implementar um try/catch dentro do while para que quando um usuário digite um double com um ponto ao invés de uma vírgula, o programa aponte o erro e mande ele de volta para a execução do código.
Porém ao testar o erro, o programa entra em um loop infinito, apenas colocando um break o programa pára de executar, mas queria saber se há a possibilidade de voltar a execução do programa sem ter que executá-lo novamente.
import java.util.InputMismatchException;
import java.util.Scanner;

public class Teste_Calc extends Calculadora {

    public static void main(String[] args)  {

        Calculadora c = new Calculadora();
        Scanner sc1 = new Scanner(System.in);
        double n1,n2;
        double resultado;
        int opcao;
        boolean x=true;

        while(x) {
            try {
            System.out.println("---------------------------------");
            System.out.println("Escolha uma das opções a seguir:");
            System.out.println("1) Somar!");
            System.out.println("2) Subtrair!");
            System.out.println("3) Multiplicar!");
            System.out.println("4) dividir!");
            System.out.println("5) Sair do programa!");
            System.out.println("---------------------------------");

            opcao = sc1.nextInt();

        if (opcao == 5) {
            System.out.println("Programa finalizado!");
            break;
        }

        else{

            switch(opcao) {

            case 1:

                System.out.println("Insita o valor do numero 1:");
            n1 = sc1.nextDouble();
                System.out.println("Insira o valor do numero 2:");
            n2 = sc1.nextDouble();
            resultado = c.somar(n1,n2);
            System.out.println("O resultado é: "+ resultado);

            break;

            case 2:
                System.out.println("Insita o valor do numero 1:");
                n1 = sc1.nextDouble();
                    System.out.println("Insira o valor do numero 2:");
                n2 = sc1.nextDouble();
                resultado = c.subtrair(n1,n2);
                System.out.println("O resultado é: "+ resultado);
                break;

            case 3:
                System.out.println("Insita o valor do numero 1:");
                n1 = sc1.nextDouble();
                    System.out.println("Insira o valor do numero 2:");
                n2 = sc1.nextDouble();
                resultado = c.Multiplicar(n1,n2);
                System.out.println("O resultado é: "+ resultado);
                break;

            case 4:
                System.out.println("Insita o valor do numero 1:");
                n1 = sc1.nextDouble();
                    System.out.println("Insira o valor do numero 2:");
                n2 = sc1.nextDouble();
                resultado = c.dividir(n1,n2);
                System.out.println("O resultado é: "+ resultado);
                break;

                default:
                    System.out.println("Opção invalida");

            }

     }
            }

            catch(InputMismatchException exception) {
                System.out.println("Caracter inserido não compatível!" );
                 continue;
            }
        }
    }
}

Comment: Tenta mudar o valor de x para false no lugar de por o break;
Comment: Você está usando o catch com o try do menu. Tem que setar o try/catch para o trecho do código que recebe o input do seu double.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: O código é confuso e por isso fica até difícil encontrar o erro, e fácil cometê-lo. É um método grande demais com muita repetição de código, mas não vou tentar arrumar isso. Pelo menos deixe as coisas mais próximas, mantenha as construções menores, não precisa ter um try tão grande. Na verdade eu sou crítico do uso de exceção para este tipo de coisa, mas aí é um erro da API do Java e você pode fazer pouco (até pode, mas dá trabalho demais), então tem que lidar com esse problema. Tirei algumas partes pra compilar já que não as tenho, mas essa herança parece muito errada também, apesar de funcionar. Veja como fica mais simples (eu nem sei onde estava o erro, eu só organizei e funcionou):
import java.util.InputMismatchException;
import java.util.Scanner;

class Teste_Calc {
    public static void main(String[] args)  {
        while (true) {
            System.out.println("---------------------------------");
            System.out.println("Escolha uma das opções a seguir:");
            System.out.println("1) Somar!");
            System.out.println("2) Subtrair!");
            System.out.println("3) Multiplicar!");
            System.out.println("4) dividir!");
            System.out.println("5) Sair do programa!");
            System.out.println("---------------------------------");
            int opcao;
            try {
                Scanner sc1 = new Scanner(System.in);
                opcao = sc1.nextInt();
            } catch (InputMismatchException exception) {
                System.out.println("Caracter inserido não compatível!");
                continue;
            }
            if (opcao == 5) {
                System.out.println("Programa finalizado!");
                break;
            } else {
                switch (opcao) {
                case 1:
                    System.out.println("1) Somar!");
                    break;
                case 2:
                    System.out.println("2) Subtrair!");
                    break;
                case 3:
                    System.out.println("3) Multiplicar!");
                    break;
                case 4:
                    System.out.println("4) dividir!");
                    break;
                default:
                    System.out.println("Opção invalida");
                }
            }
        }
    }
}

Coloquei no GitHub para referência futura.
Note como tudo eu faço mais próximo de onde é usado, inclusive declaração de variáveis.
Answer: Estou com o mesmo problema! Já tentei usar break; e depois continue;, já tentei usar if/else e parar o loop alterando o boolean e depois reativando fora do loop.
Nada funcionou.
Essa é classe:
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import tadeu.fila.labs.Documentos;
public class Arquivo {
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    Queue<Documentos> filaDoc = new LinkedList<>();

    Impressora print = new Impressora(filaDoc);

    //RESOLVER PROBLEMA COM THREAD QUE NÃO FINALIZA
    //RESOLVER PROBLEMA DE LOOP INFINITO SE DIGITAR LETRAS AO INVES DE NÚMEROS
    menu(scan, filaDoc);

}

public static void adicionarDocumento(Scanner scan, Queue filaDoc) {

    System.out.println("Digite o nome do documento:");
    String nomeDoc = scan.next();

    System.out.println("Digite a quantidade de páginas:");
    int qtdPaginas = scan.nextInt();

    Documentos doc = new Documentos(nomeDoc, qtdPaginas);

    synchronized(filaDoc) {
        filaDoc.add(doc);
    }
    System.out.println("Documento adicionado com sucesso!");
}

public static void menu(Scanner scan, Queue filaDoc) {

    boolean menuAtivo = true;
    int opcaoMenu = 0;
    while (menuAtivo) {
        System.out.println("1 - Adicionar documentos" + "\n" + "2 - Visualizar fila de impressão" + "\n" + "3 - Sair do Menu" );
        try {
            opcaoMenu = scan.nextInt();
        }
        catch(InputMismatchException e) {
            System.out.println("Digite apenas o número da opção desejada!");
        }
            menuAtivo = executarOpcao(opcaoMenu, filaDoc, scan);

    }
}

public static boolean executarOpcao(int opcaoMenu, Queue filaDoc, Scanner scan) {

    synchronized(filaDoc) {

        boolean menuAtivo;
        switch (opcaoMenu) {

        case 1:
            adicionarDocumento(scan, filaDoc);
            break;
        case 2:
            System.out.println(filaDoc.toString());
            break;
        case 3:
            return menuAtivo = false;
        default:
            break;
        }
        return menuAtivo = true;
    }
}

}
Se for necessário para entendimento, segue as outras classe:
import java.util.Queue;
public class Impressora implements Runnable{
private Queue<Documentos> doc;

public Impressora(Queue<Documentos> doc) {
    this.doc = doc;
    instanciarEStartarThread();
}

public void instanciarEStartarThread() {
    Thread t = new Thread(this);
    t.start();
}

public void run() {

    boolean rodarThread = true;
    while (rodarThread) {

        if (doc.isEmpty()) {
            try {
                Thread.sleep(10000);
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            impressaoDocumento();
        }
    }
}

public synchronized void impressaoDocumento() {

    int tamanhoDoc = doc.peek().getQtdPaginas();
    String nomeDoc = doc.peek().getNome();

    System.out.println("Iniciando impressão do documento: " + nomeDoc);

    for (int i = 0; i < tamanhoDoc; i++) {
        System.out.println("Documento: " + nomeDoc);
        int paginaEmImpressao = i + 1;
        System.out.println("Imprimindo página: " + paginaEmImpressao + " de " + tamanhoDoc);
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    System.out.println(doc.peek() + " foi impresso com sucesso!");
    doc.poll();
}

}
public class Documentos {
private String nome;
private int qtdPaginas;
private boolean documentoImpresso;

public Documentos(String nome, int qtdPaginas) {
    this.nome = nome;
    this.qtdPaginas = qtdPaginas;
    this.documentoImpresso = false; }

public String getNome() {
    return this.nome;
}

public int getQtdPaginas() {
    return this.qtdPaginas;
}

@Override
public String toString() {
    System.out.println();
    return "Documento: " + nome + ", Quant. Páginas: " + qtdPaginas ;
}

}


gulp-inject not loading all bower components

Question: I'm using the yeoman generator-gulp-angular to scaffold my app. I installed ng-18next with bower, and the package and it's dependency were both correctly installed in the bower_components directory. However, when I run gulp serve and view the source the components aren't being injected into page, so I get a module instantiation error. If I hard code the deps into the page there are no errors. I also tried bower install --save and the deps are inserted into the bower.json file correctly. Any ideas?
Thanks.
Answer: I had hard-coded script references in index.html. Even though they were commented, this caused them not to be injected with wiredep.


HOW to correctly connect to WCF service using bootstrap token

Question: I cannot find what I`m doing wrong.
When I try to call service operation I get error:
The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.
<code>    using (Ref.SService_V1_0Client client = new Ref.SService_V1_0Client("RWS"))
{
    var request = new Ref.IVISRequestStructure();
    request.Header = new Ref.RequestHeaderStructure();

    client.ChannelFactory.Credentials.SupportInteractive = false;
    ChannelFactoryOperations.ConfigureChannelFactory(client.ChannelFactory);
    ChannelFactoryOperations.CreateChannelWithIssuedToken<Ref.ISService_V1_0>(client.ChannelFactory, ((Microsoft.IdentityModel.Claims.ClaimsIdentity)(Page.User.Identity)).BootstrapToken);
    client.StartTransaction("string argument");
}
</code>
Configuration in web.config:
<code> <system.serviceModel>
  <bindings>
    <ws2007FederationHttpBinding>
      <binding name="ws2007FederationUserName" closeTimeout="00:01:00" openTimeout="00:01:00"
        receiveTimeout="00:10:00" sendTimeout="00:01:00" maxReceivedMessageSize="100000000">
        <security mode="TransportWithMessageCredential">
          <message issuedKeyType="SymmetricKey" negotiateServiceCredential="true">
            <issuer address="adress/STS/Issue.svc/trust/13/issuedtokenmixedsymmetricbasic256" binding="customBinding" bindingConfiguration="issuedtokenmixedsymmetricbasic256"/>
          </message>
        </security>
      </binding>
    </ws2007FederationHttpBinding>
  </bindings>
  <client>
    <endpoint address="another_address/servicename.svc/ws2007Federation"
      binding="ws2007FederationHttpBinding" bindingConfiguration="ws2007FederationUserName"
      contract="Ref.ISService_V1_0" name="RWS" />
  </client>
 </system.serviceModel>
</code>
Answer: Try using the return value of the CreateChannelWithIssuedToken call to invoke the service instead of using the client variable. See the CreateChannel code in this sample for how CreateChannelWithIssuedToken  is used. It would look like this:
<code>var serviceClient = ChannelFactoryOperations.CreateChannelWithIssuedToken<Ref.ISService_V1_0>(client.ChannelFactory, ((Microsoft.IdentityModel.Claims.ClaimsIdentity)(Page.User.Identity)).BootstrapToken);
serviceClient.StartTransaction("string argument");
</code>


classification based on evolution of features in time

Question: I have signals, from this signal I do windows analysis and extract features. So from 1D signals of 882000 points I get 200 vectors (200 windows of analysis) of 3 values (200*3 matrix, Let's call "InputMatrix").
I would like to make classification (in an objective of machine learning, with supervised learning), to separate 6 types (6 classes) of signals.
The differences are the time evolution of my extracted features.
What would be a good methods for this ? SVM ? Artificial neural network ?
My main question is about taking in account time evolution
2nd question : what if I get different size of "inputMatrix" for each sample ?
Answer: If I understand correctly you have 200 samples described by 3 features.
This in fact represent only one signal to classify into one of 6 categories. I then suppose you have many 1D signals to classify, which represent your dataset.
You think that your signal category can be inferred from the describing features evolutions. Even if you don't think it's smart to consider the full matrix as an input, let me try to change your opinion.
This 200 x 3 represent one sample, let's think about this matrix as an image (with your feature accordingly normalized). It could be interesting to experiment a solution with an mindset of image classification, in the sense that you would be using CNNs. By using 1d convolution of TBD size n (so with a filter of size n by 3 for first convolution layer) you could treat individual temporal slices as discriminant classifying patterns. You would be effectively calculating theses different 'temporal' activations via convolutions, merging them in your architecture and finally applying a label to it. The only difference with a classical image classification via CNNs would be that it has no sense to explore your feature dimension (so your convolution hase only one degree of freedom), only the temporal is here relevant.
This method of 1d convolution with CNNs has been used in music genre classification with great success. Your 200x3 is your music, your 6 classes the genres.


R contingency table on multiple crossed/interacted columns

Question: I was wondering if there was a way to realize 'beautiful' contingency table on R on multiple columns. I am not sure the terms I used are precise enough, so There is what I am looking for:
I start with an example of my data:
structure(list(Gender = c("Male", "Female", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Male",
"Male", "Male", "Male", "Male", "Female", "Male", "Male", "Female",
"Male", "Male", "Male", "Male", "Male", "Female", "Female", "Male",
"Female"), Race = c("White", "Hispanic/Latino(a)", "White", "White",
"White", "White", "Black/African American", "Black/African American",
"White", "Hispanic/Latino(a)", "Hispanic/Latino(a)", "Black/African American",
"Hispanic/Latino(a)", "Black/African American", "White", "Hispanic/Latino(a)",
"Hispanic/Latino(a)", "White", "Hispanic/Latino(a)", "Hispanic/Latino(a)",
"White", "Black/African American", "White", "Hispanic/Latino(a)",
"White", "Hispanic/Latino(a)", "Hispanic/Latino(a)", "Hispanic/Latino(a)",
"Hispanic/Latino(a)", "White"), Age = structure(c(1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 3L, 1L, 1L, 2L, 1L,
1L, 1L, 3L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L), levels = c("(10,30]",
"(30,50]", "(50,100]"), class = "factor")), row.names = c(7022L,
3223L, 447L, 6750L, 5255L, 9689L, 9263L, 3865L, 8891L, 6190L,
7438L, 6313L, 496L, 130L, 4771L, 4172L, 5150L, 4290L, 3960L,
3552L, 2609L, 4007L, 6725L, 520L, 8034L, 8672L, 7903L, 8693L,
9380L, 1257L), class = "data.frame")

     Gender               Race     Age
7022   Male              White (10,30]
3223 Female Hispanic/Latino(a) (30,50]
447    Male              White (10,30]
6750   Male              White (10,30]
5255   Male              White (10,30]
9689   Male              White (10,30]

I would like to create a contingency table that would give me a result like that:
                  Race
Age      Gender   Black/African American Hispanic/Latino(a) White
(10,30]  Female                      1                  1     2
         Male                        2                  6     7
(30,50]  Female                      0                  2     1
         Male                        1                  4     1
(50,100] Female                      0                  0     0
         Male                        1                  0     1

I tried using table on three variable using:
table(df[,c('Age','Gender','Race')])

But I got the following result:
, , Age = (10,30]

        Race
Gender   Black/African American Hispanic/Latino(a) White
  Female                      1                  1     2
  Male                        2                  6     7

, , Age = (30,50]

        Race
Gender   Black/African American Hispanic/Latino(a) White
  Female                      0                  2     1
  Male                        1                  4     1

, , Age = (50,100]

        Race
Gender   Black/African American Hispanic/Latino(a) White
  Female                      0                  0     0
  Male                        1                  0     1

I also tried to use interaction:
table(interaction(df$Age, df$Gender), df$Race)

I got the following result:
                  Black/African American Hispanic/Latino(a) White
  (10,30].Female                       1                  1     2
  (30,50].Female                       0                  2     1
  (50,100].Female                      0                  0     0
  (10,30].Male                         2                  6     7
  (30,50].Male                         1                  4     1
  (50,100].Male                        1                  0     1

Which are not so bad, but still not as beautiful as I'd like.
I hope I was clear, Thanks you very much for your help!
Answer: ftable(df, row.vars = c(3,1))

                Race Black/African American Hispanic/Latino(a) White
Age      Gender
(10,30]  Female                           1                  1     2
         Male                             2                  6     7
(30,50]  Female                           0                  2     1
         Male                             1                  4     1
(50,100] Female                           0                  0     0
         Male                             1                  0     1

or even
ftable(df[,c('Age','Gender','Race')])

Comment: Thank you very much! That was easier than I thought!


How to sort multiple time-series based on "shape"?

Question: Consider the following toy data:
All prices have been normalised using
$${Price_{Norm} = \frac{Price_{current} - Price_{Min}}{Price_{Max} - Price_{Min}}}$$

Item : Prices
  Apples : 0.0, 0.4, 0.8, 1, 0.7
  Bread : 0.0, 0.2, 0.4, 0.7, 1.0
  Cars : 1.0, 0.6, 0.0, 0.2, 0.1
  Wheels : 0.7, 1, 0.7, 0.2, 0.0
  Computers: 0.7, 1, 0.3, 0.0, 0.6

At first glance, we can see which items can be seen as being correlated. The price of food went up, and price of automobiles went down.
I can use the mean squared error to find the distances between the items, but is it possible to both sort by the shape and by trend?
Items to the left should have the most upward trend and at the right, downward trends. Similar items (using mean squared error on each point) should be as close to each other as possible.
On this toy data, it is very easy:
Bread, Apples, Computers, Wheels, Cars
But I am lost when trying to do this on hundreds of time-series.
Where should I get started? I am a beginner in these types of problems.
Comment: Proper normalization can tricky in general, and it's particularly problematic when it's based on extreme values (max, min) over a set of time-series observations. Extreme values often aren't well enough behaved to serve well for reliable normalization. Please edit your question to say more about what you are trying to accomplish rather than focusing on the approach you are already taking, as there might be much better ways available to address the issues you care about.
Answer: You can only sort well by one criterion; you cannot meaningfully sort 2d data.
To sort by your notion of 'trend', I suggest you compute the correlation with a straight upwards line each. I.e. correlation.with 0.0,0.25,0.5,0.75,1.0, then sort all by this score. Cars will have a negative correlation, and thus come late.
Comment: Is it not possible to sort 2D data or do some kind of abstract representation of it based on a "shape" metric? And correlating with a straight upwards line is problematic as these two data are considered equal, but they are not the same shape in time: 0, 1, 1, 1, 1 and 0, 0, 0, 0, 1
Comment: I'm not suggesting to treat this to be *enough*. But these two have the same overall trend! The impossibility of ordering 2+ dimensions consistently follows from the inability to order the complex numbers. You can only sort by a derived value such as the sum or the concatenation.
Comment: So either you reduce your requirements (e.g. the correlation score I suggested) or you don't expect it to be based on sorting.
Answer: Sorting in 2d can be tricky, but I think if you want to understand the strength and direction of the pairwise correlations, then a scatterplot matrix (SPLOM) might be useful.
This R-bloggers post found a nice function called ggcorplot by written by Mike Lawrence that highlights the correlations by color and size opposite the corresponding scatter plots.

https://www.r-bloggers.com/five-ways-to-visualize-your-pairwise-comparisons/
Comment: This is generally a good approach, but the question asks about visualising patterns in 'hundreds of time series'. Scatterplot matrices are not practical at that scale.


Android Server response special chars ��������������V*�I

Question: I got a problem with my Android response. I checked every step with this server and I can't get a solution. Here is detailed info:
URL: https://XXX/public/api/versions/published/2/1408
METHOD: GET
Request header:
Status  Complete
Response Code   200 OK
Protocol    HTTP/1.1
SSL TLSv1.2 (TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
Method  GET
Kept Alive  No
Content-Type    application/json

Header response:
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.4.2

Expected response:
{
    "platform": "Android",
    "number": "5.5.3",
    "force_update": false
}

Android received response:
05-16 14:09:40.500 12368-12425/com.screens D/OkHttp: --> GET https://XXX/public/api/versions/published/2/1408 http/1.1
05-16 14:09:40.500 12368-12425/com.screens D/OkHttp: --> END GET
05-16 14:09:40.700 12368-12425/com.screens W/System.err: org.json.JSONException: Value ��������������Kn� of type java.lang.String cannot be converted to JSONObject

Server ssl_protocols:
TLSv1 TLSv1.1 TLSv1.2;
Server charset:
UTF-8
Android Http client library:
Retrofit 2.3.0
Comment: You're probably using the wrong encoding.
Comment: `and accept all Certs` You have no security whatsoever.  **Don't do that!**
Comment: Either.  You need to use the same encoding (which should almost always be UTF8) at both ends.  You need to learn how Unicode encodings work.
Comment: Where? In my server or in my app? @SLaks "and accept all Certs" -> only for tests :( and nothing
Comment: Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions.
Comment: Please read [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions.
Comment: @SLaks No, don't is an encoding problem
Answer: You're getting a Gziped response, and your app is not being able to parse it.
Make sure that a gziped response is supported in the app.


Uncaught TypeError: Object [object Array] has no method 'serialize'

Question: mybook.push({
            pages: $("#id_pages").val()
           });

mybook.serialize()

Error:

Uncaught TypeError: Object [object Array] has no method 'serialize'

How to fix it?
Comment: what is `invoiceItems`
Comment: yes because this `mybook` is not a jQuery object, its an array.
Comment: You should show how you define the variable invoiceItems.
Comment: Should you not be serializing mybook, rather than invoiceItems?
Comment: But i think you can `console.log($(mybook).serialize())`
Comment: what you are trying to achive?
Answer: Actually mybook is not a jQuery object,As of jQuery API you should pass it to jQuery Class then you can use the method .serialize() or .serializeArray()
console.log($(mybook).serialize())
Comment: How to build JSON string from `mybook` array?
Comment: check this answer http://stackoverflow.com/questions/2295496/convert-array-to-json?answertab=active#tab-top


Jumbotron and Footer are not stretching out to the width of the Mobile Phones Screen Device

Question: Clicking inspect on Google Chrome. When I scroll down the page on the "Toggle Device Toolbar" option. My Jumbotron and Footer are not stretching out to the phones full screen width. I have the code pushed onto CodePen.io for you to look at. The link is provided below. I've also noticed when inspecting the body tag in the html, it gives me exactly where the cut off is occurring.
CodePen.io
https://codepen.io/alexbritoofficial/pen/MWYpbRg

Answer: This is because class row has margin-left:-15px & margin-right:-15px which is just under the class w-100 which has width:100! important; I made changes to 2 instances below:

Instance1: You can remove row because you are not using the col-** classes
Instance2: Since you do have col-** classes under it, you add a container-fluid around it so that row doesn't go out of the screen view

body {
  height: 100%;
  background-color: #fccd4d;
}

.myNavbar {
  background-color: black;
}

.jumbotron {
  background-image: url("/Project/img/Unknown.png");
  height: 400px;
  background-size: 100% 100%;
  margin: inherit;
}

/* Navigaton Bar List Items CSS */

.menuItems {
  white-space: nowrap;
}

.listItem {
  padding-left: 30px;
  padding-right: 30px;
}

.listItemText {
  font-family: "Calistoga", cursive;
  color: white;
  white-space: nowrap;
  display: inline-block;
  font-size: 18.2px;
}

.listItemText:hover {
  color: white;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: black;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: white;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-family: "Calistoga", cursive;
}

.dropdown-content a:hover {
  background-color: #bd3f055b;
}

.dropdown:hover .dropdown-content {
  display: block;
}

.hrSeperator {
  border-color: black;
}

.divSpacer1 {
  height: 10px;
}

.appetizersH1 {
  font-family: Georgia, "Times New Roman", Times, serif;
  font-weight: bold;
  color: black;
}

.container {
  padding-top: 50px;
}

.main-container {
  padding-top: 10px;
}

/* Menu Choice Item Styling */

.menuChoiceItem {
  white-space: nowrap;
  font-family: Georgia, "Times New Roman", Times, serif;
  font-size: 30px;
  font-weight: bold;
  color: black;
}

.footerContainer {
  justify-content: space-between;
  height: 300px;
  background-color: black;
  margin: inherit;
  display: flex;
}

.coastCafeFooterH1 {
  white-space: nowrap;
  font-family: "Girassol", cursive;
  color: white;
}

.coastCafeFooterParagraph {
  white-space: nowrap;
  font-family: "Girassol", cursive;
  color: white;
}

.plate-identifier {
  font-family: Georgia, "Times New Roman", Times, serif;
  color: black;
}

blockquote .menu-item-h1 {
  font-family: Georgia, "Times New Roman", Times, serif;
  color: black;
  font-weight: bold;
}

.appetizer-description {
  color: black;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/css?family=Calistoga&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Gelasio|Girassol&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="CSS/menuCSS.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, intial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie-edge" />

      <button class="navbar-toggler" data-toggle="collapse" data-target="#collapse_target" style="
        background-color: yellow;">

        </button>

             Home

              Our Story

                Our Menu

              Appetizers
              Combination Plates
                  Coast Specialties
                  Chicken Boxes
                  Classic Sandwiches
                  Signature Sides
                  Homemade Desserts

                Catering

                  Request an Event

        Order Online

              Contact Us

            Appetizers

              Corn Bread

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

$4.00

              Beef Patty

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

$4.00

              Beef & Cheese Patty

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

$4.00

              Chicken & Cheese Patty

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

$4.00

              Jerk Chicken & Cheese Patty

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

$4.00

              Buffalo Chicken & Cheese Patty

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

$4.00

              Fries

            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis,
            consequuntur.

            (Sm) $4.00

            (XL) $4.00


How to filter checkboxes using JQuery 2.1.4?

Question: I am trying to select and de-select all check boxes given in table column. I have already done code for JQuery version 1.4.0 but, after upgrading version to 2.1.4 it has stopped working.
The problem where I am getting in my code is here:
function findCheckBoxes(selectid, table) {
    return $(table).find('td input:checkbox:not(:disabled):[id*=' + selectid + ']');
}

It is throwing error:
Uncaught Error: Syntax error, unrecognized expression: td input:checkbox:not(:disabled):[id*=chkselect]

If I remove the further filter from the find function then it works fine but, I also want to filter the disabled and specific column checkboxes.
function findCheckBoxes(selectid, table) {
    return $(table).find('td input:checkbox');
}

But, It selects all checkboxes not from particular column.
Here is my fiddle
Answer: The problem is the : before [id*= which creates an invalid selector
$(table).find('td input:checkbox:not(:disabled)[id*=' + selectid + ']');

Demo: Fiddle


Recommend a desktop app to monitor port 80 on servers

Question: I did some googling but was unsuccessful, so I am posting here. I am looking to get an app (preferably free/open source) to monitor my servers on port 80 that would send me an email/text when some predefined timeout triggers. I could probably write something in VB to do this but i am burried with projects, why reinvent the wheel. I know there are services out there that want you to pay $5/month to do so, I was thinking about a Windows app that would sit on my computer and simply monitor predefined list of IPs on port 80.
Thanks!
Comment: nagios - its massively overkill for what you suggest - but costs nothing, is reliable, and very extendable.
Comment: symcbean - will it install on windows?
Comment: http://nagios.sourceforge.net/docs/3_0/about.html#requirements says not.
Answer: You should check out Pingdom.  It's mainly a web app that will send you e-mail/text notifications for any downtime, and the timing is configurable.  It comes with a Windows app that will notify you if a site goes down.  It's free for a single site, and has a monthly fee for additional sites and other features.  I know it's not the same as just a desktop app, but it'll work better if you need reliable monitoring.
Answer: In Linux box you can do a little script for monitor webservers.
A example of the script (put in the webserverlist.txt file all the servers that you want to monitor and set the params of timeout as you need):
<code>#!/bin/sh

serverlist=`cat webserverlist.txt`

for i in $serverlist; do
echo $i
        wget --connect-timeout=2 --read-timeout=5 $i 2>&1
        if [ $? -eq 1 ]; then
                echo "ALARM: Webserver $i no OK" | mail -s "ALARM: Webserver $i no OK" firstname.lastname@example.com
        fi
done
</code>
Comment: thanks Mitch, anything for windows? :)
Comment: Install cygwin, then you can run this script in windows easily. Lifehacker.com has a decent intro: http://lifehacker.com/179514/geek-to-live--introduction-to-cygwin-part-i
Answer: quick and free monitoring app
http://polymon.codeplex.com/
Comment: thanks, i am checking out this app but its really confusing, the full version that requires database needs plugins in order to monitor TCP ports, but i cant find them anywhere on the site. the Real Time version does not monitor TCP ports.... :| am i missing something?
Comment: sorry I've been on vaca, but the non real time one will monitor a website out of the box no plugins necessary.  I have not used the real time one so I don'
t know anything about that.
Answer: PRTG Network Monitor will do the trick for you. The free version allows up to 10 sensors, more then sufficient for a simple web server.
http://www.paessler.com/download/prtg
Remember to request the free license too.
The installation is a breeze. Simple and straightforward and awesome amount of features.


Scores are still correlated after PCA

Question: I have 22 variables with more than 6000 observations. They are highly correlated. I know these data would work as great explanatory variables to a dichotomous event (present absent). Therefore, I intend to combine them via binary logistic regression and, so to avoid multicolinearity, I thought of "orthogonalizing" the original data using PCA. Then I could choose the main modes of variability (or even all the PC's) and use them as the explanatory variables in my regression, once PCs are orthogonal and independent, by definition.
I am running this in MATLAB with function pca. The variables are nearly normally distributed and are first normalized between 0 +/- 2 standard deviations (around zero because it will be interesting to keep their signal for future analysis, I believe). I also chose not to center the data within the MATLAB function, once they're already normalized.
Now here comes the pitfall. My first 2 PCs (scores) are correlated with r=0.7891! Any hints on this? Any suggestions on mistakes I may be making?

EDIT: In case it lightens th scenario, here is a biplot. Letting PCA center the data, I believe the cloud would be just displaced to around the origin, but still keeping its format / correlation, correct?
Comment: Hint: Center your data.
Comment: Orthogonality and correlation are different things unless the vectors are centered.
Comment: ddavid, In your PCA analysis, you should have kept consistent. If you do usual, consensual PCA, you center the data first (i.e. do the analysis based on covariances). Principal directions are extracted and PC scores are computed with that centered data. _Correlations_ (or covariances) between the PCs will be zero. But if you do PCA on raw, uncentered data (i.e. based on [SSCP](https://stats.stackexchange.com/a/22520/3277) matrix) you should logically use raw data to compute PC scores...
Comment: (cont.)  Such scores will also have zero associations among themselves; but these implied associations are not correlations but sscp crossproducts (or cosine similarities). Thus, PCA violated nothing. It supported "orthogonality" in both cases. The thing is in this: what is to be the proper association implied as orthogonalized: correlation or what? With raw data, it is not correlation.
Comment: Please see question https://stats.stackexchange.com/q/73319/3277 which is similar in the issue raised. And general Q https://stats.stackexchange.com/q/22329/3277.
Comment: Please see http://stats.stackexchange.com/questions/22329 and also http://stats.stackexchange.com/questions/189822
Comment: @whuber, indeed I was missing that. But anyways, is it not the main feature o PCA to obtain uncorrelated scores? Should the simple subtracting from a constant mean of the variable (i.e. centering) affect the results so expressively? Thank you.
Comment: `but still keeping its format/correlation, correct?` - Incorrect :) Try it.
Comment: yes @amoeba, just tried it seconds after the edit.. thank you :)
Comment: The first paragraph in [my answer to a related question](http://stats.stackexchange.com/a/35190/919) contains additional commentary on what centering the variables accomplishes.
Comment: @whuber, in the cited paragraph, you explain that the first PC would be a vector of means and the subsequent PCs would be orthogonal to it. I still find strange that the orthogonal PCs 1 and 2 were so strongly correlated. The orthogonality makes them linearly independent, so I hoped for a bit less correlation as well, no?
Answer: Remember how PCA works: It starts by finding the single dimension (direction) of greatest variation in your dataset.  That becomes PC1.  Then it finds the direction of greatest variation that is at right angles to that.  It becomes PC2.  Etc.
The important thing to recognize is that if your data aren't centered, the direction of greatest variation might well be from the origin of the space (e.g., $(0, 0)$ in a Cartesian plane) to the centroid (mean vector) of your data.  Every subsequent principal component is constrained by that first one:  They all have to be at right angles to it.  That means that the resulting PCs may not uncorrelate your data.
Here is a quick illustration (written in R):
library(MASS)   # we'll use this package
set.seed(7668)  # this makes the example exactly reproducible
X = mvrnorm(100, mu=c(-5, 0), Sigma=rbind(c(1,  1.6),   # here I generate data
                                          c(1.6,  4) ))

windows(height=4, width=7)
  layout(matrix(1:2, nrow=1))

  plot(X[,1], X[,2], xlim=c(-8, 1))
  abline(h=0, col="gray");  abline(v=0, col="gray")
  points(mean(X[,1]), 0, pch="*", cex=2, col="red")

  biplot(prcomp(X, center=FALSE))

Scores are still correlated after PCA


"representative sampling" from a distribution

Question: I'm drawing samples from a distribution to train a machine learning classifier (training it via mini-batches of 32 samples at a time). It's just a toy dataset, so I know that the samples are coming from a multivariate Gaussian with an identity co-variance matrix.
Since the quantile function (inverse CDF) is tractable for such a distribution, I could evenly space the samples across the domain (0,1) of this function (e.g. points of the unit square in the 2D case) and presumably get a mini-batch of sample the encompass the entire distribution. Obviously I'd have to add a random offset to this grid of samples such that every mini-batch isn't identical, but otherwise it seems like this should speed up learning  alot. My question is: is this approach reasonable or is there something I'm missing? And if it is, then is there name for it or literature around it?
Thanks!
Comment: The domain of the inverse cumulative density function of the 2D Gaussian is [0,1]^2, which is what I was refering to
Comment: The domain of the 2D Gaussian isn't [0,1]^2, but R^2.  If your question is just to sample from the distribution, please read http://stats.stackexchange.com/questions/12953/generating-values-from-a-multivariate-gaussian-distribution.
Answer: Frame the problem this way:
You have a distribution $P$ over a set $\mathcal X$, a classification loss function $L : \mathcal X \to \mathbb R$, and the gradient of the loss function with respect to an input sample $g : \mathcal X \to \mathbb R^d$. You want to know $\mathbb E_{X \sim P}[ g(X) ]$ in order to take a step in your optimization algorithm.
The typical way to do this in machine learning is to suppose that you have a sample
$\{ x_i \}_{i=1}^N \sim P$, and estimate $$\mathbb E_{X \sim P} [ g(X) ] \approx \frac{1}{N} \sum_{i=1}^N g(x_i).$$
(Thinking about it this way makes clear the motivation for stochastic gradient descent, where you simply take a subset of your training sample at each step.)
What you're proposing instead is that instead of just taking a random sample $\{ x_i \}$, you carefully choose a set of points to represent the distribution. It turns out this is an idea that makes a lot of sense, and is generally known as quasi-Monte Carlo. If you assume that the function $g$ is relatively smooth, and the dimension of $\mathcal X$ is not too high, then there are specially designed sequences of points you can use to guarantee that your estimate is not too different from the true expectation.

Note that everything I just said only applies to a single step of the optimization algorithm. As you noted in the question, if you choose the same $\{ x_i \}$ every time, you may end up at a weird optimum that works well for those points but not in general. A satisfying theoretical answer to this problem will probably take some work, but I think in practice if you just randomly shift the points (as you suggested) then it should be okay in "reasonable" cases.
Comment: Thank you soo much! That quasi-Monte Carlo link just saved me a bundle of time :D


Adding html to t() in Drupal 6 template.php?

Question: Hi I am trying to add html to the "t('Older Posts')" and "t('Newer Posts')" Is this possible ? I can figure it out ????
I am in a Drupal 6 template.php file.
This is the code I am trying to add as html -
 Newer Posts
 Older Posts

I need to replace the above in these spots located in the full function below ?
 t('Older Posts')
 t('Newer Posts')

I want to create something like this
 t('Older Posts')
 t('Newer Posts')

Full Function
 function theme_views_mini_pager($tags = array(), $limit = 10,
 $element = 0,  $parameters = array(), $quantity = 9) {
 global $pager_page_array, $pager_total;

 // Calculate various markers within this pager piece:
 // Middle is used to "center" pages around the current page.
 $pager_middle = ceil($quantity / 2);
 // current is the page we are currently paged to
 $pager_current = $pager_page_array[$element] + 1;
 // max is the maximum page number
 $pager_max = $pager_total[$element];
 // End of marker calculations.

$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] :
t('Older Posts')), $limit, $element, 1, $parameters);
 if (empty($li_previous)) {
$li_previous = " ";
}

$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('Newer Posts')),
$limit,$element, 1, $parameters);
if (empty($li_next)) {
$li_next = " ";
}

if ($pager_total[$element] > 5) {
$items[] = array(
  'class' => 'action back pager-previous',
  'data' => $li_previous,
);

$items[] = array(
  'class' => 'action pager-next',
  'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}

I am trying to figure out if this is possible I have tried many things and nothing has worked yet.
Comment: There appears to be a lot of discussion on the titled topic here:  http://drupal.org/node/322774
Answer: You should probably look into overriding the pager theme functions instead.

theme_pager_previous
theme_pager_next
Answer: I would do it more like this:
$html = '';
$html .= t('Older Posts');
$html .= '';

Comment: yeah that still output plain text I wanted it to change the output of the views pager and still encode as html in the browser not plain text sorry that may have been unclear