Como criar arquivo.php utilizando php?

Question: A ideia é montar um sistema de notícias, assim que eu preencher a página de notícias e clicar em publicar, deve gerar um arquivo .php com o conteúdo da notícia.
Fazer esse conteúdo eu devo conseguir, eu só queria saber como eu faço para gerar esse arquivo.php utilizando o proprio PHP.
Comment: Não deveria usar o banco de dados para armazenar as informações? se quiser criar o arquivo é só usar o `file_put_content()` ou `fopen()/fwrite()`
Comment: A melhor solução é armazená-la em banco de dados mesmo. Se não souber, essa é a melhor hora para aprender. O que você pode fazer depois é gerar páginas HTML estáticas para servir de cachê, mas começa primeiro servindo o conteúdo dinâmico a partir do banco.
Comment: @NicolasGuilhermeMatheus, Cara até existem possibilidades de você fazer isso, mas não é viável não, seu site vai ficar muito vulnerável, nunca permita o próprio usuário escrever um arquivo php, php é uma linguagem a nível de servidor. Crie um banco de dados onde você armazene esses textos e exiba os conteúdos usando templates.
Comment: https://forum.imasters.com.br/topic/427668-criar-arquivophp-com-php/
Comment: eu não sei, sou novato, a ideia era criar o arquivo e deixar o arquivo com o conteúdo dentro no banco, como seu eu tivesse criado manualmente, como se fosse estático
Comment: eu pensei em criar um banco e armazenar os textos lá, porém não sei como dar continuidade no processo, alguém tem algum tópico que eu possa estudar sobre o assunto?
Answer: Basicamente:
<?php

     $conteudo = '<?php phpinfo(); ?>';

     file_put_contents('novophp.php', $conteudo);

Manual:

http://php.net/manual/pt_BR/function.file-put-contents.php

Ou assim:
$conteudo = '<?php phpinfo(); ?>';

$arquivo = fopen('novophp.php', 'w');
fwrite($arquivo, $conteudo);
fclose($arquivo);

Manual:

http://php.net/manual/pt_BR/function.fopen.php

http://php.net/manual/pt_BR/function.fwrite.php

Tendo respondido, algumas considerações
Provavelmente não é isso que você quer. Antes de mais nada, para fazer o que foi proposto, precisa ter permissões de escrita nos diretórios onde for gerar os PHP. Além disso, a manutenção seria extremamente sofrida quando o conteúdo fosse alterado. Provavelmente, como já comentado, você deveria pensar em uma opção com base de dados.
Existem casos legítimos onde gerar um .html estático pode ser interessante, e economizar muitos recursos do servidor, apenas alterando e/ou removendo esses arquivos quando alterar algo no DB. Eu acho uma estratégia muito boa para sistemas de CMS, mas deixe isto para quando dominar o essencial.
Comment: @NicolasGuilhermeMatheus não uso frameworks em PHP. Tem quem goste, não é meu caso. O que o PHP tem de nativo é mais eficiente e vai direto ao ponto para praticamente qualquer coisa. Quando você chegar na parte de rotas (decidir o que fazer conforme o URL que o usuário digitou), se fizer um _benchmark_, vai ver que  os frameworks em geral costumam ser uma "carroça" comparado a soluções diretas, como arquivos separados e boa organização. FW de PHP usualmente serve para "pensar menos" e "enrolar cliente". Nenhuma das 2 coisas me interessa :)
Comment: Sim, estou pensando na versão utilizando banco de dados, estou estudando para conseguir fazer isso, sem utilizar framework eu consigo fazer isso?

Como criar arquivo.php utilizando php?


Matrices and linear maps End($V$) of infinite dimension

Question: I am struggling to understand the following concept required to solve a task that I found in my Algebra book.
The task: Let $V$ be (a possibly infinite-dimensional) vector space and $A$ an endomorphism. Furthermore let $\sigma(A)$ be the set of Eigenvalues of $A$ (analogously for the endomorphism $B$). Show that $\sigma(AB)\setminus\{0\}=\sigma(BA)\setminus\{0\}$.
My initial instinct was to represent $A$ and $B$ as $n\times n$ matrices and do some brute-force calculation and show that the characteristic polynomials of $AB$ and $BA$ are similar. However, I am having second doubts regarding the representation of $A$ and $B$ as $n\times n$ matrices as I cannot represent the basis of $V$ in only $n$ variables (it might be infinite-dimensional).
This concern left me in doubt whether I should solve it with matrices at all or somehow express the eigenvalues through $(A\circ B)(v)=\lambda v$. Any clarification would be much appreciated!
Answer: The idea or motivation from the finite dimensional case is that $AB$ and $BA$ are "almost similar." Like, we have $B(AB)B^{-1} = BA$ except $B$ might not be invertible. So you have to work around the non-invertibility by assuming you're not in $\ker B$ or something like that.
So suppose $v$ is an eigenvector of $AB$ corresponding to a non-zero eigenvalue $\lambda$. Then what we would like to do is define a vector $w$ such that $B^{-1}w = v \iff w = Bv$ and then we have
$$BAw = B(AB)B^{-1}w = B(AB)v = B(\lambda v) = \lambda Bv = \lambda w.$$
Now this works fine if $B$ is invertible. If $B$ is not invertible then all we need to do to fix this is to cut out the second expression:
$$BAw = B(AB)v = B(\lambda v) = \lambda Bv = \lambda w.$$
Therefore $\lambda$ is an eigenvalue of $BA$ corresponding to the non-zero (!!) eigenvector $w = Bv$.
Comment: Thank you for your answer! Would you mind elaborating on 1) Why $w$ cannot be zero. 2) Why you can assume that $\lambda\neq 0$. Consider the following: Suppose $v$ is an eigenvector of $AB$ s.t. $AB(v)=0$. Therefore $B(v)\in\ker A$. Now let $w=B(v)$ and therefore $BA(w)=BAB(v)=B(0)=0$ so that $\lambda=0$ is a common eigenvalue of $AB$ and $BA$.
Comment: @EdwardTeach I take $\lambda \neq 0$ because we're trying to show $\sigma(AB)\setminus\{0\}=\sigma(BA)\setminus\{0\}$. We know that $Bv \neq 0$ because $ABv \neq 0$.
Comment: Right, because $v\neq 0$. As a side question: Why doesn't $\sigma(AB)=\sigma(BA)$ hold for infinite-dimensional spaces? However, I will mark your answer as the solution and would like to thank you for your help!
Comment: @EdwardTeach Take $V$ to be the space of infinite sequences $(a_0,a_1,\dots)$ and let $A$ shift the sequence to the left (deleting $a_0$) and $B$ shift the sequence to the right. Then $AB$ is the identity and $BA$ has a non-trivial kernel.


Variables in for loops

Question: Hello I am new to coding and have chosen to start off with the language python 3.x. I am running into a problem as when I declare a variable and insert it in a for loop the variable is not changed.
This can be seen as after running the code below the output remains as the original value of 5.
    i = 5

    for x in range(2):
     i + 1

    print(i)

Answer: You use i = ... to give it a value, then you do not use i = ... anywhere to give it a new value, so the value never changes. You need:
i = 5

for x in range(2):
 i = i + 1

print(i)

i + 1 alone is not an error, but it does the calculation and throws the result away, as you did not say what else to do with it.

Variables in for loops


Writing for Violins and Violas

Question: I'm studying some classical compositions to see how to write properly for the string section. One thing I've noticed is that the Viola bar often has two notes playing at the same time whereas the Violin 1 & 2 often are playing single notes.
My confusion is mainly: how does one Viola section play two notes at the same time? Do they simply play the dyad on their instruments? Or does one half of the stands play the top and the other the bottom?
How does this translate to violins? I sometimes see separate Violin sections play dyad/octaves. In what cases is it acceptable to write these instead of just giving each section of the orchestra 'their own note'?
Answer: An extended passage with two notes at all times is almost certainly intended to be divided. Dividing into two or three parts is very common, but as a composer, you can decide to divide the section as many ways as you want. I've personally seen up to 8-way divisi--of course, you wouldn't want to try to jam that all on one staff though!
You should divide if it's even remotely complex. Double stops should be used with caution in ensemble music, and there's a lot of nuance to whether a particular double stop will be easy or hard.
Answer: It may be a double stop - two (or even more if we allow an arpeggio gesture) strings played at once.  It may be a divisi - two (or more) notes divided between two (or more) groups of players.  Divisi should be notated clearly, but sometimes isn't!    And it isn't unknown for players to decide that a double stop would sound better as a divisi.   Composers and arrangers sometimes delight in 'stretching the limits' unnecessarily.
Also - yes, a violin CAN play a passage in octaves.  But it's clumsy and will be out of tune.  Use that possibility sparingly.
Comment: "A passage in octaves is clumsy and will be out of tune" – unless we're talking about a Paganini-proof virtuoso, of course. Normally, a reasonable string section will play such stuff divisi even when the score doesn't say so, except perhaps in some 20th century music where the intended effect is evidently more _make loud, jarring noise_, than anything else.

Writing for Violins and Violas


Finding the euclidean centers of the geodesics AB, AC, and BC

Question: I am trying to learn about finding the angles in hyperbolic geometry and I am trying to understand this example given in Stahl's Introduction to topology and geometry.
You can notice that there is a yellow line, the author mentions that it is clear the euclidean centers of the geodesics $AB$, $AC$ and $BC$ are $P(2,0)$, $Q(4,0)$, and $R(6,0)$. However it is not so clear for me, how did the author obtain these coordinates or atleast one of them?
Answer: I suppose the author uses the Poincare half plane model ( https://en.wikipedia.org/wiki/Poincar%C3%A9_half-plane_model )
where hyperbolic lines (geodesics) are half circles centered on the boundary line (x axis)
Given that the points are the same distance of the boundary line / x axis there center is halfway the two points on the xaxis.
and this way he gets to the points $P$ $Q$ and $R$
the angles are the angles between the half circles
Hopes this helps
PS i don't own Stahls book so cannot go deper than this


Como ajusta minha data da minha query?

Question:

$result_usuario = "SELECT * FROM vendas WHERE DATE(date_created) = '$data' AND
tipo_venda = '$tipo_vendas' AND tipo = '$tipo_pagamento' ORDER BY 'id'";

Tenho essa query, mas a mesma não funcionar direito pois o input que preencher a variável '$data' vem com o formato '12/11/2018' e o formato que conta na colona 'date_created' e '2018-12-11', como faço pra ajusta a minha query??
Answer: Use uma função que irá servir para duas entradas dd/mm/YYYY ou YYYY-mm-dd.
function inverteData($data){
    if(count(explode("/",$data)) > 1){
        return join("-",array_reverse(explode("/",$data)));
    }elseif(count(explode("-",$data)) > 1){
        return join("/",array_reverse(explode("-",$data)));
    }
}

$data = "12/11/2018";

//para usar na query
$dataInvertida = inverteData($data); //2018-11-12

//alguma data retornada do select
$dataBanco = "2018-11-21";

$dataBancoInvertida =  inverteData($dataBanco); // 21/11/2018

exemplo no ideone
$result_usuario = "SELECT * FROM vendas WHERE DATE(date_created) = '$dataInvertida' AND
tipo_venda = '$tipo_vendas' AND tipo = '$tipo_pagamento' ORDER BY 'id'";

Answer: Tem várias formas de fazer isso. Recomendo o seguinte:
// Recebe a variável com a data, e cria um objeto DateTime a partir do formato especificado.
$objetoData = DateTime::createFromFormat('d/m/Y', $data);

// Reformata a data do jeito desejado
$data = $objetoData->format('Y-m-d');

Depois é só usar a variável $data da forma que você estava fazendo.
Answer: Já que você precisa apenas fazer a consulta, pode trazer a sua coluna date_created do select formatado como precisa.
DATE_FORMAT(date_created, '%d/%m/%y')

Aqui tem maiores informações sobre a função date_format

É possivel fazer através do PHP também.
Transformando a data que você recebe no padrão utilizado pelo BD.
$dataFormat = DateTime::createFromFormat('d/m/Y', $data);

E para utilizar depois você pode formatar ela para o padrão necessário
$data = $dataFormat->format('Y-m-D');

Como ajusta minha data da minha query?


How to decide between module_exists and function_exists?

Question: I'm familiar with using module_exists in a module, and using it in situations like:

Enable some extra functionality in a module, provided some other module is available in the site also. The Reservations: Email module contains an example (actually there are plenty of examples of this), as shown in its module source: to use tokens (in the eMail body) requires that the Token module is enabled.
Implement module dependencies in a theme, as shown in the answer to "How to implement module dependencies in a theme and package modules with a theme?".

However, there is also function_exists, such as shown in the answer to "Is it possible to declare a Javascript library dependency at Hook.info?".
I have the impression that using function_exists is a more robust (safe) approach as compared to module_exists. Especially if you want to be sure that some function (added in a newer version of a module) is available, whereas by just using module_exists, you risk to run into errors like those:

if a site is still using an old version of a module, which doesn't have that function yet (so you shouldn't try to use it  yet).
if a site is already using an new version of a module, which doesn't have that function anymore (so you shouldn't try to use it  anymore).

My question: what are the typical criteria, or pros/cons, to decide for using either  module_exists versus function_exists?
Answer: You should always program to the API and not the implementation.  If Drupal provides a mechanism to do something, use it.
module_exists() should almost always be used for soft dependencies on something provided by a Drupal module.  You can always get version info, and decide what to do, using system_get_info().  There have been cases where functions are available when modules have been disabled (some of the class autoloader modules have has this problem).
function_exists() should be reserved for checking whether a PHP feature or library is available.  Core has some examples of this in some of the drupal_ wrappers for string manipulation and character set conversion.
Answer: module_exists is a Drupal API function used to determine whether a module is installed, it isn't designed to give any guarantees of the functionality a module might contain, including what functions it declares.
function_exists is a PHP core function which literally determines whether a function with a given name exists in the current request.
As such, they aren't really comparable with one another, you use them for different things. In fact it would be easy, albeit potentially redundant, for them to complement one another, e.g.
// Do something with a specific module
if (module_exists('foo')) {
  // Check what's available
  if (function_exists('foo_bar')) {
    // ...
  }
  elseif (function_exists('foo_baz')) {
    // ...
  }
}

Comment: I agree ***they aren't really comparable with one another***
Comment: Do you mean the library module check in `MODULENAME_requirements` in the linked post? Yes, that would make more sense as a call to `module_exists`. As MPD mentioned, the higher-level/more abstracted way to ensure that a dependancy has certain functionality is to examine the code for a release, and make your code rely on a specific version that you know your code works with. Just like Composer/NPM/Bundler/etc do it
Answer: You are right, function_exists is a more robust way to check the existence of the API function provided by contrib module. It is very suitable for directly using the contrib module's API.
I use Session Cache API as an example:
if (function_exists('session_cache_set')) {
  session_cache_set($bin, $data)
}

However, some contrib modules only provides some extra properties or feature, it is very hard to say which dependent function is. In this case, you need to use module_exists
I use Elements as an example:
if (module_exists('elements')) {
  $form['url'] = array(
    '#type' => 'urlfield',
    // other code
  );
}
else {
  $form['url'] = array(
    '#type' => 'textfield',
    // other code
  );
}

Comment: How would you know whether `session_cache_set` is being provided by https://www.drupal.org/project/session_cache or another module, and therefore does what you want?
Comment: @MPD It depends on if you believe in everyone using the same naming strategy as suggested. `function_exists` can prevent undefined function error when the contrib module did change its API after update. Of course, the most guarantee method is wrap `function_exists` with `module_exits` as @Clive mentioned, but, to me, it is too tedious.
Comment: @MPD Theoretically, replying interface is a better approach, and I would love to follow. But in practical, `function_exits` indeed prevent the site from completely brokering down...
Comment: Interesting! I'll need some more time to "digest" ...
Answer: The prior 3 (interesting) answers appear to me as somehow confirming my "perception" (as I described in my question). Interestingly enough, those answers were originally written independent from each other (they were posted at more or less the very same moment, as illustrated in the timeline of this question, use the "toggle format" to see "mins").
Jimmy Ko's answer (+ comments below it), illustrates some more examples of how using function_exists can make a module more robust with respect to possible changes in some other module that a module uses (depends on).
Clive's answer shows you could as well combine module_exists and function_exists, while the comment below it resolved my doubts about my function_exists example (ie it should rather use module_exists).
mpdonadio's answer (+comments below it) is, at least to me, the toughest to digest. But after reviewing Shawn Conn's comment below it, I found a few more links that provide more details about all this, i.e.:

Program to an interface, not an implementation.
From SO: What does it mean to "program to an interface"?.
From programmers.SE: Understanding "programming to an interface".

"My conclusion" (after digesting the previous answers): Leave it to Drupal core to use function_exists, and contributed/custom modules should try, as much as possible, to stick to module_exists ... though there are exceptions ...


Ruby: Calculate sum of all node values of a binary tree

Question: I have a binary tree implementation as below. I'd like to add a method that recursively sums up all node values of the binary tree:
class BST

  class Node
    attr_reader :value, :left, :right

    def initialize(value)
      @value = value
      @left = nil
      @right = nil
    end

    def insert(value)
      if value <= @value
        @left.nil? ? @left = Node.new(value) : @left.insert(value)
      elsif value > @value
        @right.nil? ? @right = Node.new(value) : @right.insert(value)
      end
    end

  end

  def initialize
    @root = nil
  end

  def insert(value)
    @root.nil? ? @root = Node.new(value) : @root.insert(value)
  end

end

I found the answer for other languages, however unfortunately not for Ruby.
Comment: What do you mean, you found the answer for other languages but not for Ruby? The logic is exactly the same. What specifically is the obstacle you are facing in implementing it?
Comment: @Amadan I'm a beginner and trying to understand recursion. While I do understand the principle, I'm unable to transpose other languages' solution into Ruby...
Comment: The sum of a node is the the node's value plus the sum of all non-nil children, right? At least attempt to translate it into code, then we can talk about what is wrong with it, if anything.
Comment: A good start would be to add an example of a tree (and show the value of the desired sum). As there are no answers yet you might consider deleting the question, edit to clarify and add an example, then undelete. That way you won't feel time pressure to complete the edit and won't attract more downvotes or votes to close while you are editing. SO has a rule that, for homework problems (not suggesting this is one), the asker is expected to explain efforts he/she has made to solve the problem. That does not necessarily require code. It's potentially a good question.
Comment: Re: "The sum of a node is the the node's value plus the sum of all non-nil children, right? At least attempt to translate it into code". Here is what I tried inside the BST class:

  `def sum(node=@root)
    return if node.nil?
    total += node.value
    sum(node.left)
    sum(node.right)
  end`

however it throws "NoMethodError: undefined method `+' for nil:NilClass". This is where I get stuck.
Comment: In general, try to write code in questions/answers, as code in comments that is longer than one line is superhard to read. If you must, then use `;` (or whatever is appropriate in your language) to separate the statements. I'll try to answer based on what I think you meant...
Answer: I think your code in the comments was:
def sum(node=@root)
  return if node.nil?
  total += node.value
  sum(node.left)
  sum(node.right)
end

The idea is almost okay. There is no summing in nil nodes; and you total up the current node's value, the left node and the right node. Here's the mistakes:

total += node.value is the first time we see total. This initialises it to nil. When you try to add node.value to it, you get the error you described. To avoid it, either total must already exist, or you can just assign node.value to it.
If a function ends without executing a return statement, it returns the last evaluated expression; in this case, sum(node.right). Wouldn't it be better if sum returned total?
Conversely, sum(node.left) will presumably do some summing... but its return value is discarded. It might make sense to add it to the total. Speaking of totals, maybe we should do the same for sum(node.right).
Finally, return if node.nil? says you refuse to sum the nodes that are not actually nodes. That's great... except that return returns nil, and if you try to total a nil with something, it doesn't go well. There are two solutions here: refuse to total a node before you enter it, or say that a nil node has value 0, which does not affect a sum.

Taking it all together, here's my two versions:
# refuse to enter a nil node:
def sum(node=@root)
  total = node.value
  total += sum(node.left) unless node.left.nil?
  total += sum(node.right) unless node.right.nil?
  total
end

# treat nil nodes as if they were zeroes:
def sum(node=@root)
  return 0 if node.nil?
  node.value + sum(node.left) + sum(node.right)
end

Comment: Thank you very much for your detailed answer! It explains exactly all the issues that I was struggling with all along and had me scratch my head for days until I finally resorted to SO. Also thanks for guiding me through the usage of SO, thanks also to @ Cary !

P.S. My attempted upvote is not being recorded due to my too low reputation score... Thanks again - you were super helpful!


Exporting from Field Collections and Importing to New Content Type

Question: So here's a high-level overview of the situation: we're running into a lot of issues with the field collections module, but a lot of content has already been created for a content type that uses two fields within a field collection. We've tried to overcome some of the problems we're experiencing with field collections, and at this point it's been over a month, so we're just going to have to give up on field collection for this project.
So here's what we have. A content type like this:

Title Field
Field Collection field containing:

Subtitle Field
Body Field

And we want to export from that and create nodes in a content type that looks like this:

Title Field
Subtitle Field
Body Field

I don't really need past revisions or anything like that. I'm just looking for advice about how best to accomplish this.
Answer: Some time ago I did something similar, but with normal fields. I used Views Bulk Operations.
First I've created a view which listed all the nodes of the particular node type and added the VBO checkbox to execute arbitrary PHP code.
On the view's page I've checked all the nodes and pasted in the PHP textbox the code which updated field B values based on the field A values. In your case you should create a new node based on the field collection.
Finally, when VBO finished executing the code for all my nodes, I went to the content type fields page and deleted field A (in you case the field collection).
Done!
Comment: This sent me down the path to solving this issue. Views Bulk Operations are where it's at. I'm marking this as the answer since this is a really excellent tool for grabbing a big chunk of data for an Import.
Comment: I'm glad that I could help! :)
Answer: After creating your new content type you can try to use either Rules, Feeds or the Migrate module to move the existing content into new nodes.
I've successfully used the Migrate module to create Field Collections for example (and update a node with Field Collections). I know the other 2 approaches are doable too. Unfortunately, I dont have any simple code examples to share with you.
Comment: I will definitely look more closely at Migrate as my team tries to figure out the best way to handle exporting/importing of data.


add new row to data frame with list type column

Question: I would like to have multiple elements per cell in a particular column of a data frame. There is a note at R-bloggers explaining how to do so with lists:
> d <- data.frame(id=1:2)
> d$name <- list(c("Bond", "James"),c("Poppins", "Mary"))
> d
  id          name
1  1   Bond, James
2  2 Poppins, Mary

So far so good. But now I would like to add further rows to the data frame. This is the result:
> d[nrow(d) + 1,] <- list(3, c("Hood", "Robin"))
Warning message:
In `[<-.data.frame`(`*tmp*`, nrow(d) + 1, , value = list(3, c("Hood",  :
  replacement element 2 has 2 rows to replace 1 rows
> d
  id          name
1  1   Bond, James
2  2 Poppins, Mary
3  3          Hood

The second element of the vector is discarded. How can I convince R to add the second element to the name cell too?
Answer: We can use add_row
library(tibble)
add_row(d, id = 3, name = list(c('Bond', 'Robbin')))
#  id          name
#1  1   Bond, James
#2  2 Poppins, Mary
#3  3  Bond, Robbin

Regarding the way to assign next row, we have a list of list as the 2nd column
d[nrow(d) + 1, ] <- list(3, list(c("Hood", "Robbin")))
d
#  id          name
#1  1   Bond, James
#2  2 Poppins, Mary
#3  3  Hood, Robbin


Multilevel Menu but all in the same drop down?

Question: How would you create a menu in Drupal where you had multiple levels, but they were all displayed in the same dropdown but with the child menu items indented.
e.g.
<code>Parent 1
 Child 1
 Child 2
 Child 3
Parent 2
Parent 3
</code>
Answer: Bootstrap has recently removed the sub-menu features from version 3.x, so it won't support the multi-level menu anymore. But drupal 8 has multi-level menu structure. I am going to show you how to get back the sub menu features in bootstrap and how to render multi-level menu in the drupal 8. Just copy and paste the following css in your custom css, its has been taken from the bootstrap version 2.x with some custom changes, The following article would help to create multi-level menu in drupal 8


I need to implement ignite into existing NODE js project. I read documentataion of apache ignite but could not find out how to start

Question: I need to implement apache ignite in existing NODE js project. I read apache ignite documentation but unble to find from where to start and how to change queries from existing one. I create a NODE in java but how to link that node with node js thin client.
Answer: Have you tried copying & modifying some of Node.JS examples, such as SqlExample.js?
More are available through Ignite Node.JS docs section.
Comment: Thank you for your respone.
I read above documentation and tried to run existing node js files and they are working fine. but when i create my own code. it gives me error.
Comment: Please share that error along with your code in a separate dedicated question.


Having trouble making a scatterplot out of my data in R studio.

Question:
As the title says. Instead of a typical scatterplot with an x and y axis, I get something with a third increment on the right side of the graph. What am I doing wrong?
Comment: It looks like line 1 has the column names, this would coerce the data into character and so your plot is like a barchart of character numbers.
Comment: you need header=TRUE in your read.table arguments
Answer: In this dataset, there is a mistake in the first row which is supposed to be the row names rather than the first row. R then assumed that your columns are of class Factor.
To solve it use
<code>read.table(...,header=TRUE)
</code>


A mouse leaping along the square tile

Question: A $n \times n$ square is made of square tiles of dimensions $1\times1$. A mouse can leap along the diagonal or along the  side of square tiles. In how many ways can the mouse reach the right lower corner vertex of the square from the lower left corner vertex of the square leaping exactly  $n$ times?
In one of my exam, I encountered a particular version of this problem with $n=5$. With a semi-brute force (case counting) kind of approach I derived the answer as $21$. How to derive the general solution for any $n \in \mathbb{N}$ ?
Comment: Is there any particular reason that it is a square? if I get the problem correctly the mouse will never get higher than $\frac n2$ for any suitable path.
Comment: What do you mean by "leap"?  By diagonal leap, do you mean just single steps, or any move to any other point on the same diagonal? Does the mouse move like a chess king, or a chess queen?
Comment: Thomas: more like a king
Answer: The general solution is the $n$th Motzkin number $-$ the number of ways of drawing non-intersecting chords between $n$ points on a circle. There is a Wikipedia article on Motzkin numbers, and an entry (A001006) in the OEIS database. The OEIS entry gives several recurrence relations and generating functions, but they are all very messy.
Comment: @Thomas: I think you have misunderstood the OP's question. Also, it seems that you didn't read the Wikipedia article I linked to (or even look at the pictures).
Comment: From the Wiki article, that seems like it might be a little off - the "path" version is the number of paths of length $n$ from $(0,0)$ to $(0,n)$.  But the OP's question is asking for paths of length $n$ from $(0,0)$. to $(0,n-1)$, or else you'd be dealing with an $n+1\times n+1$ grid.  In particular, the Motzkin example never requires all steps to be at least to the right.
Answer: You will find a mass of formulae at OEIS A001006
If I were working this out from scratch I would use
$$\sum_{k=0}^{\lfloor n/2 \rfloor} {n \choose 2k} \frac{1}{k+1} {2k \choose k} =\sum_{k=0}^{\lfloor n/2 \rfloor} \frac{n!}{k! (k+1)!(n-2k)!}$$
as a combination of $k$ diagonal up steps, $k$ diagonal down [but not going below the starting point so involving Catalan numbers] and $2n-k$ horizontal.
So for $n=5$ this gives $\dfrac{5!}{0!1!5!} + \dfrac{5!}{1!2!3!} + \dfrac{5!}{2!3!1!} = 1 + 10 + 10 =21.$

A mouse leaping along the square tile


AJAXifying content and pagination problems

Question: I am using the Ajax links API module that allows to load a node inside a
 tag by using Add page.
However, I have a problem: If I use a pager, and I click on the link to see another page, I will be redirected to that page, instead of loading it inside the
 tag.
I solved partially by using the Views Infinite Scroll module, but if I have several
 tags, the module doesn't load the correct view in the correct
.
It seems I cannot use the pagination because the URL is not re-written to accommodate to the container, and it is not scrolling because this limitation.
Is there some way of creating simple AJAX calls loading content in different
 tags on the same page, and with pagination (or load more button, infinite scrolling, etc.)?
Comment: Looks like you are not the only with "Ajax not working on Ajax Loaded Content". Found below link which could be helpful for you. https://www.drupal.org/node/1877446 To be honest i haven't tried to replicate your problem, but i think you should find solution in patch #15, as stated in comments by quite a few people.
Comment: You are trying to do this using Views Module...right?
Comment: Right, with module Views.
Comment: Please check if you have Ajax: Yes in your View.
Comment: Yes, I have Ajax: Yes checked, and the URL link displays the &ajax=1 parameter. However, as the class "ajax-link" is not used not rewritten in the pager, when clicking on Next page, it directs the browser to another page, instead of loading the content with Ajax.
Answer: Try this below solution with views pager ajax enable.
jQuery 1.7+ Version
function runthiscode() {
  $(".pager a").each(function(){
    $(".pager a").addClass("ajax-link");
    $(".pager a").attr('rel', '#content')
  });
}

$(document ).ready(function() {
  runthiscode();
});

$(document ).ajaxComplete(function() {
  runthiscode();
});

Comment: While I solved the problem by uninstalling modules, deleting cache, and low-level database entries, this solution will work in other general instances, mainly on Nested Views and the like, so IMHO it deservs the 50 points bounty.
Answer: It seems your problem is similar to Ajax pager does not work as expected for nested views, I had this problem before and  patch #15 help me to resolve.
take a look  and try that if it not work tell me I suggest you another solution
Comment: Applying a patch is literally one command... learn it. Some patches are so large you are bound to miss a change by manually copy pasting over things.
Comment: I have never used pathcing nor Drush. I am not sure why this problem is not solved in the main code.
Comment: @Cesar what is your operation system? mac? windows? linux?
what is your IDE ?
Comment: Windows XP, Aptana and FTP, with XAMPP for testing.
Comment: @Cesar  I *Suggest*  learn how to patch, really it's good for you .
very easy way to apply patch( this is traditional and not recommend method ) is manually patching : "
open `views/js/ajax_view.js` file, and also open
www.drupal.org/files/issues/1877446-15-views-ajax-pager-closest-parent_1.patch ,  remove each line in `ajax_view.js` when you see has **-** in *patch* and also add lines to `ajax_view.js`  that has *+* mark."
Also read this about  "patch" for Windows XP
 www.drupal.org/node/23844
Read this one too stackoverflow.com/questions/517257/how-do-i-apply-a-diff-patch-on-windows
Comment: I will try to learn how to patch someday in the future. Meanwhile, I will follow your by-hand avcisee, -- = remove line, ++ = add line, keeping a save copy. Thanks for your explanations.
Comment: @Cesar you're welcome, inform me fro the result and if you need help feel free, we are here to help other drupalists
Comment: Now after deleting all, and creating the View from scratch, if I activate Use Ajax in the View, it will work perfectly, as it should have from the beginning. No need of patch, which may be ok for nested views. I will try to have a nested view and replicate the results, I think that there were some conflicts among modules and now that I cleaned it completely, the problem does not manifest itself.
Comment: @Cesar congratulations :)
Answer: Try this with below jquery solution.
jQuery 1.7+ Version
function runthiscode() {
  $(".pager a").each(function(){
    var a_href = $(this).find('a').attr('href');
    $('.pager a').on('click', function(event){
      $("#content").load(a_href+" #content");
    });
  });
}

$(document ).ready(function() {
  runthiscode();
});

$(document ).ajaxComplete(function() {
  runthiscode();
});


Noncomplete riemannian manifolds

Question: In Lee's Riemannian manifolds text, he claims that "on $\mathbb{R}^n$ with metric $(\sigma^{-1})^* g$ obtained from the sphere from stereographic projection, there are geodesics that escape to infinity in finite time."
(To be clear, $g$ is the round metric on the sphere being pulled back to $\mathbb{R}^n$ via stereographic projection.)
This is supposed to be in contrast to Hopf-Rinow, but I'm completely confused: $\mathbb{R}^n$ IS a complete metric space. So this would be a counterexample to Hopf-Rinow, which is absurd....
Comment: $\mathbb{R}^{n}$ is a complete metric space with the standard metric. Completeness depends on metric.
Answer: A space is geodesically complete if all geodesics exists for all time. With the standard metric on $\mathbb{R}^n$, the geodesics are exactly straight lines parameterized by constant speed, and have a full domain $\mathbb{R}$, or are constant curves. The geodesics of the stereographic projection metric reach infinity in finite time.
It is also nice to see that if $n>2$ the points $(-x,0,\ldots,0)$ and $(x,0,\ldots,0)$ get close to each other if $x\rightarrow \infty$. Thus these spaces are also metrically incomplete.
What happens for $n=1$?

Noncomplete riemannian manifolds


How to Pad several rows of string in a listbox in C#

Question: So I have been trying to display my row of strings in the listbox. However, no matter what I try the padding of each of the string seems screwed up.
What should I do? Anyone know a way to pad strings correctly in a listbox?
I tried altering values of the formatting function I am currently using, as it worked previously for me. I changed the values from +ve to -ve, but it all just didn't add up. It wasn't functioning the way it should.
Here is the formatting code I used:

format = "{0, -30}{1, -30}{2, -30}{3, -30}{4, -30}{5, -30}";
listBoxLandowners.Items.Add(String.Format(format, "Landowner ID", "First Name", "Last Name", "City", "Street", "Street Number"));

SQL.selectQuery("select * from Landowner", null, null);
if(SQL.read.HasRows)
{
     while(SQL.read.Read())
                {
                    _landID = SQL.read[0].ToString();
                    _fName= SQL.read[1].ToString();
                    _lName = SQL.read[2].ToString();
                    _city = SQL.read[3].ToString();
                    _street = SQL.read[4].ToString();
                    _streetNum = SQL.read[5].ToString();
                    listBoxLandowners.Items.Add(String.Format(format, _landID,
                    _fName, _lName,_city, _street, _streetNum));
                }
            }

Actual outcome:

I want it to pad correctly and neatly, but couldn't get it to work.
Help would be much appreciated.
Comment: With a proportional font a character like 'w' is going to take more room than 'i'. String padding cant overcome that
Comment: What kind of "listbox" are you using? UWP? ASP.NET? Show your XAML or .cshtml.
Comment: Why not use a `ListView` instead, which is meant for this kind of columnar display.
Comment: The quickest fix is to use a fixed-width font like Courier New. However you really shouldn't be using a ListBox for multi-column display (except in MS Access, which supports multiple columns). In WinForms you should use a DataGrid or a ListView.
Comment: Alright, ill try using a listview.
Comment: Sorry if this is a noob question, but. What is the difference between listview and listbox? Does Listview also allow for user interactions? like if they click on a row it does something else.
Answer: In WinForms, ListBox is not a very good control for multiple columns.
Try using a ListView in Details mode.
var listviewLandOwners = new ListView();
listviewLandOwners.View = View.Details;

When in this mode, the first column is controlled by the Text property of the ListViewItem. The second column is controlled by SubItems[0]. The third is SubItems[1]. Etc. So your loop might look like this:
while(SQL.read.Read())
{
    var newItem = listviewLandowners.Items.Add(SQL.read[1].ToString());
    newItem.SubItems.Add(SQL.read[2].ToString());
    newItem.SubItems.Add(SQL.read[3].ToString());
    newItem.SubItems.Add(SQL.read[4].ToString());
    newItem.SubItems.Add(SQL.read[5].ToString());
}

Comment: Using it in detail mode doesn't display anything. But when using the View.List it works, but the same problem still arises.


Ionic 3 LocalStorage sumindo

Question: Tenho uma aplicação em Ionic 1 que salva algumas informações no localStorage.
Reescrevi a mesma aplicação em Ionic 3 com o mesmo package id(widget id no config.xml), mas ao instalar a aplicação nova por cima da antiga eu perco o localStorage, ele vem vazio.
Se eu instalar novamente a antiga por cima da nova eu consigo enxergar novamente o localStorage, é como se fossem aplicações diferentes, mas estão com o mesmo package id e eu sempre instalo uma por cima da outra.
Isso acontece apenas no celular, as aplicações não estão compartilhando o mesmo localStorage. Ao acessar o Devtools do google na aba "Application" - "Storage" - "Local Storage" aparece "file://" quando rodo a aplicação criada em Ionic 1 e aparece "http://localhost:8080" quando rodo a aplicação criada em Ionic 3.
Tem alguma particularidade no Ionic 3 que não consegue enxergar/acessar o localStorage do Ionic 1 e vice versa?
Answer: A localStorage não é um local seguro para guardar dados. Os dados periodicamente podem ser apagados pelo sistema operativo. A melhor solução é usar o "Native Storage": https://ionicframework.com/docs/native/native-storage/

Ionic 3 LocalStorage sumindo


Find a submersion $\varphi :U\to \mathbb{R}^{n-m}$ such that $\varphi^{-1}(\{0\})=M$ in which $M\subseteq\mathbb{R}^n$ is smooth submanifold

Question: Let $M\subseteq\mathbb{R}^n$ be a $m$-dimensional smooth submanifold. We can prove that for all $p\in M$ there're an open neighborhood $U\subseteq\mathbb{R}^n$ of $p$ and a submersion $\varphi :U\to \mathbb{R}^{n-m}$ such that $\varphi^{-1}(\{0\})=U\cap M$.
My question is: can we prove that  for all $p\in M$ there're an open neighborhood $U\subseteq\mathbb{R}^n$ of $p$ and a submersion $\varphi :U\to \mathbb{R}^{n-m}$ such that $\varphi^{-1}(\{0\})=\color{red}{ M}$?
I tried to answer the above question using the partition of unity but I failed. I also don't know any counterexample.
Thank you for your attention!
Comment: Not true as stated (though it's a bit of a technicality): If $M$ is not closed in $\mathbb{R}^n$ (for instance an open disk embedded in $\mathbb{R}^3$), then $\varphi^{-1}(0)=M$ can't happen, since the first set is closed by continuity.
Answer: If $M$ is globally defined by as the preimage of $0\in \mathbb{R}^{n-m}$ under a submersion $\phi$ then the normal bundle of $M$ has a global frame defined by $(\operatorname{grad} \phi_1, \ldots, \operatorname{grad} \phi_{n-m})$, so it's trivial. This imposes some conditions on the manifold. In particular it has to be orientable ( since the ambient $\mathbb{R}^n$ is). I am not sure whether the triviality of the cotangent bundle implies the existence of a globally defined equation, but I am inclined to think so.
As a concrete example, take a non-orientable manifold like the Klein bottle imbedded in $\mathbb{R}^4$.
$\bf{Added:}$ The condition is also sufficient. As @Kajelad: indicated, we should consider a tubular neighborhood $U$ of $M$, which is diffeomorphic to the total space of the normal bundle. If the bundle is trivial, we can define $\phi= (\phi_1, \ldots, \phi_{n-m})$ ( the pullbacks of the coordinates in a trivialization) to define $M$ locally on $U$ as $M= M\times \{0\} = \{ \phi=0\}$.
Comment: The converse is indeed true, provided we're talking about embedded submanifolds. You can construct the submersion using the trivialization of $NM$ and a tubular neighborhood of $M$.
Comment: @Kajelad: I think it should work. So an open tubular neighborhood is diffeo to the total subspace of the normal bundle, so I can define  $\phi = (\phi_i)$ on that tubular. OK, I can extend them to the whole $\mathbb{R}^n$.  Now I see that the natural condition is $\phi$ is a submersion on a nbhd of $M$. To be a submersion everywhere is a bit excessive.  Perhaps I should mention that.  Thanks for the input!


MS SQL Server Service Does not start

Question: <code>Log Name:      System
Source:        Service Control Manager
Date:          11/1/2011 2:01:13 PM
Event ID:      7000
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      Admin-PC
Description:

The SQL Server (SQLEXPRESS) service failed to start due to the following error:
The system cannot find the file specified.

Event Xml: <Event
 xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
 <System>
     <Provider Name="Service Control Manager" Guid="{555908d1-a6d7-4695-8e1e-26931d2012f4}" EventSourceName="Service
 Control Manager" />
     <EventID Qualifiers="49152">7000</EventID>
     <Version>0</Version>
     <Level>2</Level>
     <Task>0</Task>
     <Opcode>0</Opcode>
     <Keywords>0x8080000000000000</Keywords>
     <TimeCreated SystemTime="2011-11-01T08:31:13.333398700Z" />
     <EventRecordID>176909</EventRecordID>
     <Correlation />
     <Execution ProcessID="556" ThreadID="5360" />
     <Channel>System</Channel>
     <Computer>Admin-PC</Computer>
     <Security />   </System>   <EventData>
     <Data Name="param1">SQL Server (SQLEXPRESS)</Data>
     <Data Name="param2">%%2</Data>   </EventData> </Event>
</code>
Comment: Next time try putting this into an actual question, rather than a statement.
Answer: Check the properties for the service, specifically the "path to executable" value.  Verify that the file reference in that value actually exists.
Answer: I have experienced same problem and i have resolved just stopping SQL Browsing service.
So give it a try.

MS SQL Server Service Does not start


How can I list all npm packages with above X downloads?

Question: I'm looking for some API that allows you to request "names of all npm packages with above X downloads". A curl command to do this would be great but if someone knows where I can get the data I could write my own script for it.
Answer: A similar question has been asked before but nobody seems to have a nice answer for it. Most depended packages is easier if that also fits your need.
You can also use https://github.com/npm/registry/blob/master/docs/download-counts.md to query for stats for individual packages, though this probably isn't efficient enough.


Z scores derived from a regression equation in one group applied to other groups

Question: I work in the developmental psychology arena.
Often papers report using regression to derive a function of age onto a score in a typical group and then applying this function to a second atypical group, saving the residuals then transforming these to z scores in respect to the typical groups mean and standard deviation.
I have derived the regression function intercept and slope, for example 5.5 + (.05*age)and applied it to all children. Then computed the residual (actual - predicted) for all children. I then applied the z score equation (z = x - mean /sd) using the mean and SD of the typical groups' raw residuals. This results in a mean of zero and sd of 1 for the typical group and mean z scores much lower (as might be expected)in the atypical group.
The alternative was not to use the mean and sd of the typical group and generate the z scores from all children in the group, whereby the mean z scores of the TD group are now higher than zero and the z scores reflect the distance from the mean of only my sample.
My question is whether this is what others mean when they use this to standardize the sample and is there anything incorrect in either way of calculating these scores?
Thanks in advance.
Answer: There are, I think, multiple uses of the term "standardize" in this sort of situation.
For diagnostic purposes, on a test that has been standardized on some group, we use that mean and sd. For example, IQ tests are normed for different ages to have a mean of 100 and sd of 15 (or 16 for some tests). We can then compare either an individual or a group to that mean and sd.
But if the test isn't normed (perhaps it is a new measure) or if our purpose is not to compare to a normed group, then I think either of the methods you describe could be called "standardizing". That is, you have tested two groups. You can standardize within each group or across the two groups. Or, if you want to attempt to replicate the first purpose with a new measure, you could norm it within the typical group and use those norms on the atypical group.
Authors should state more detail than just "we standardized the scores". They should state what mean and sd they used to do the standardization. I've seen this stated in many articles, but some authors are careless about it.
Comment: Thank you Peter for your answer, it is very much appreciated. I am reassured that I've worked through the problem correctly and understand what the differences are. If I get published I'll ensure to state clearly how the scores were calculated.


Check if user_picture value is changed or compare with old value

Question: I am trying to find if a field value is changed or updated by the user. But there are blockers.
function custom_form_process_user_picture(&$form, FormStateInterface &$form_state) {
  $file_name = "";
  $username = "";
  $fid_0 = NULL;
  $user_picture = $form['user_picture'];
  $uid = $form_state->getValue('uid');
  if ($form_state->hasFileElement() && $form_state->hasValue('user_picture')) {
    $username = $form_state->getValue('field_name')[0]['value'];
    $fid_0 = isset($form_state->getValue('user_picture')[0]['fids'][0]) ? $form_state->getValue('user_picture')[0]['fids'][0] : $fid_0;
    /*
      $changed = $form_state->get('user_picture')->getValue() == $form_state->getValue('user_picture');
      //This is not working as $form_state->get() returns null.
    */
    /*
      $changed = $form_state->get('user_picture')->getValue() == $form['user_picture']['#default_value'];
      //This is not working as $form['user_picture']['#default_value'] is null.
    */
      if($changed) {
        // Proceed to rename the file.
      }
    }

What piece of the code I am doing wrong? Searched drupal and stackoverflow for the changed/updated/dirty field value. Also tried with $form_state->getFormObject()->getEntity() and got no clue if there is old value stored or not.
FormStateInterface seems to have no method to find out altered/modified values.
Comment: Can you explain a little what you are trying to accomplish?  This hook may not be the right place to do what you need.
Comment: I want to change the file name but when edit the form value gets replaced. I am using `MYMODULE_form_alter` and this is `$form['#validate']` method.
Answer: Perhaps you should use hook_entity_presave that keeps the old (original) value
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  if($entity->getEntityTypeId() == "file"){

    $filename = $entity->getFilename();

    $file_old = $entity->original;

    if($file_old != null){
      $filename_old = $file_old->getFilename();

      if($filename_old !== $filename){
        $entity->setFilename('newfile.jpg');
      }
    }
  }
}

The function above changes the filename if its not the same as old filename.
Depending on your use case you might want to apply the above logic when user is presaved
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity)
  if($entity->getEntityTypeId() == "user"){

    // get specific field by field machine name
    $file = $entity->get('field_file');

    // or get the user_picture field
    $picture = $entity->get('user_picture');

    $user_old = $entity->original;
    // drill down in the old user object to see values changes
    // and do appropriate changes
  }
}

Comment: `MYMODULE_file_presave` should fire but on my code I am actually checking whether the entity is a file (if statement).  I have added some more details in the answer.   image is actually a file with restrictions ;-)
Comment: Can I not replace _`entity`_ with `file` or `image`??? `MYMODULE_image_presave` or `MYMODULE_file_presave` hooks are not triggering. I updated drupal, db, files and version.
Comment: Thanks, is am doing `MODULENAME_entity_presave` works somehow. And it's the better way to achieve this. I was doing it all wrong.


Got an updateTotal() not defined error. updateTotal() Function seems to be defined and called appropriately. Why would I be getting this error?

Question: updateTotal() function not defined, however, i have the function defined inside of $(document).ready( function () { and have called updateTotal() inside of other methods where it needs to be used. Running total not updating. console is showing an updateTotal() not defined.
Why could i be getting this error?
$(document).ready( function () {

 $('#plan').on('change', function() {
   var priceText;

   switch(this.value) {
     case 'monthly':
      priceText = '10.00 /mo';
      break;
     case 'quarterly':
      priceText = '$9.00 /mo';
      break;
     case 'yearly':
      priceText = '7.00 /mo';
      break;
   }

   $('#price').text(priceText)
  });

 function updateTotal() {
  var total = 0;

  var entries = $('.entry')

  if (entries.length)
    $('#empty').show();
  else
    $('#empty').hide();

  $('.entry').each( function(index, entry) {
    var data = $(entry).data();
    var price = parseFloat(data.price)
    var installment = data.plan
    switch(installment) {
      case 'monthly':
        total += price;
        break;
      case 'quarterly':
        total += price * 4;
        break;
      case 'yearly':
        total += price * 12;
        break;
    }
  })

  $('#total').text('$' + total);
}
});

$('#add').on('click', function() {
  var plan = $('#plan')
  var installment = plan.val();
  var price = $('#price').text();
  var inCart = $('#in_cart');
  var numeric = price.replace(/[[A-Za-z$\/\s]/g, '');
  var data = 'data-price="' + numeric + '" data-plan="' +
  installment + '"';
  inCart.append('
' + installment + ' - ' + price + '<button
 class="remove">X</button>
')
  updateTotal();
});

  $(document).on('click', '.remove', function() {
  $(this).parents('li').remove();
  $('#empty').on('click', function() {
    $('#in_cart').empty();
    updateTotal();
  });

});
Comment: Suggested Duplicate: [What is the scope of variables in javascript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript)
Answer: Functions in JavaScript are scoped in global or function scope, so updateTotal is visible only in document.ready function.
You should try to define updateTotal in global scope (outside document.ready) or create some common scope using IIFE (https://developer.mozilla.org/en-US/docs/Glossary/IIFE) to not to populate global scope too much.
Some info about scoping:
https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
Comment: thanks! error went away after defining function outside of document.ready
Comment: After debugging, I discovered the function did in fact need to be inside document.ready. The inCart.append line was not written properly. Needed an  and also needed to append price.


How to push the contents of the HTML while opening the side navigation bar?

Question: Here is the snap of the website
On this image as I have provided after appearing of the side navigation bar the Hamburger icon and company images are hiding and how to close this side navigation bar using bootstrap, css.
Comment: This link here shows how to do a push navigation. https://www.w3schools.com/howto/howto_js_sidenav.asp
Answer: You can use JQuery to move the company logo and hamburger icon to the right upon the opening of the navigation and move back left upon closing of the navigation. If I'm reading correctly. It is a little hard to understand your question.
Just an example as I don't have actual code to reference.
<code>$('.navbar-toggle').click(function(){
     if($(this).hasClass('collapsed'){
          //set position to relative if not set
          $('.logo').css({'position':'relative','left':'100px'});
          $(this).css({'position':'relative','left':'100px'});
     }else{
          //set back to 0 or original position
          $('.logo').css({'left':'0px'});
          $(this).css({'left':'0px'});
     }
});
</code>


What's the difference between Ctrl+C and Ctrl+[?

Question: What's the difference between Ctrl+C and Ctrl+[? The documents contain the following that I can find:
<Esc> or CTRL-[ End insert or Replace mode, go back to Normal mode.  Finish
                abbreviation.
                Note: If your <Esc> key is hard to hit on your keyboard, train
                yourself to use CTRL-[.
CTRL-C          Quit insert mode, go back to Normal mode.  Do not check for
                abbreviations.  Does not trigger the |InsertLeave| autocommand
                event.
CTRL-C                  Interrupt current (search) command.  Use CTRL-Break on
                        MS-DOS |dos-CTRL-Break|.
                        In Normal mode, any pending command is aborted.
It seems there is some disagreement to what exactly the commands do.
Does Ctrl+C not also leave Replace mode, and how do abbreviations relate to pending commands?
Comment: duplicate: http://stackoverflow.com/questions/80677/what-is-the-difference-between-c-c-and-c-in-vim
Comment: The duplicate remains unsolved, and does not address the question regarding abbreviations and pending commands.
Answer: It helps to think of CtrlC in vim the same way you think of CtrlC in a shell - you want to stop whatever you were doing ASAP and get control back. So in vim, if you're using CtrlC to break out of insert mode, vim isn't going to bother checking if you just wrote part of an abbreviation, and it isn't going to run the fancy auto commands your plugins have set up for every time you leave insert mode, it's just going to dump you back in normal mode as soon as it can. If you're not using abbreviations or autocmds, then you're not going to notice this difference.
Comment: Ahhh, that nails it, thanks. I wasn't aware there were mode-changing hooks.


Insert php com objeto como parâmetro

Question: Gostaria de entender como posso fazer uma função de inserção no php que usa um objeto como parâmetro. Exemplo:
<code>class Aluno{
   private $nome;
   private $curso;
}

getters e setters...

public function insere(Aluno $aluno){
// suponho que aqui fica a definição dos atributos e o retorno do mysqli_query (não tenho certeza)

}
</code>
A minha dúvida é como eu posso fazer com que essa função possa inserir um registro no banco, quando ela simplesmente for chamada por um objeto instanciado. E gostaria que essa função não sofresse alterações no parâmetro, mesmo que se coloque mais atributos na classe. Preciso que sempre seja um objeto Aluno. Também gostaria de entender como posso usar o retorno dessa função.
Comment: Primeiro é importante que você relacione sua entidade aluno do banco(tabela) com sua classe Aluno. Depois é só efetuar o insert into normalmente, usando os getters para atribuir os valores das colunas da tabela.
Comment: Qual é realmente o problema ? É difícil perceber, qual é realmente o problema tendo este exemplo como base, e a tua explicação também não está clara ?
Comment: Edilson, eu disse acima que preciso entender como posso fazer uma função usando um objeto como parâmetro, eu não entendo exatamente como devo implementar a função, eu até coloquei um comentário supondo o que acredito que deve ser, mas não tenho certeza de como fazer.
Answer: Olá, boa noite.
Sou iniciante em php, e também não utilizo o mysqli (estou utilizando PDO),
<code>$pdo = new PDO("mysql:host=localhost;dbname=nome_banco", "usuario_banco", "senha_banco");
$insert = $pdo->prepare("INSERT INTO NomeTabela (nome,curso) VALUES (:nome,:curso);");
$insert->bindValue(":nome",$aluno->nome);
$insert->bindValue(":curso",$aluno->curso);
$insert->execute();
</code>
Comment: Concaternar valores no SQL cria uma vulnerabilidade de segurança (SQL Injection). Imagina se alguém coloca como nome:
"; DROP DATABASE; --
Comment: Olá, Obrigado pelo comentário, tinha respondido quando comecei os estudos em php/banco de dados. Fiz as modificações.

Insert php com objeto como parâmetro


Keeping track of changes to a System during Software/Patch Installation

Question: Let's say I'm installing a software on Windows and I want to see all the changes it has made during its installation, what is the easiest way to keep track of system changes. The change could happen in program/system files or registry etc., Is there a tool that tracks that changes? This could be useful in, for example, a patch installation where an administrator may want to keep track of all the changes it has made.
Comment: Practically a duplicate of [Program to snapshot changes made during an install?](http://serverfault.com/questions/388037/program-to-snapshot-changes-made-during-an-install)
Answer: You want to do the "poor man's snapshot". I do this fairly frequently when building my own MSIs for third-party software w/ WIX.
Process Monitor is probably a bit too verbose for what you're trying to do. You might try making a "snapshot" of the registry using something like:
<code>REGEDIT /E BEFORE.REG
</code>
And then again afterward so you can compare.
With the filesystem, I've used the freeware utility "FileList" to generate a "before" and "after" snapshot of the filesystem.
Modifications inside existing files are problematic. You might have to take an initial snapshot, locate files that have been modified, then roll-back (I normally use a VM and the built-in disk snapshot functionality for roll-back) and take a "before" snapshot of each file that you know is going to be modified to compare to the "after" version.
Remember that capturing what changes isn't the same thing as capturing the logic of the setup program. Where possible, reverse-engineering the setup program is preferred to just trying to capture what changes. You may miss nuances that you aren't seeing because of circumstances of your snapshot computer's configuration.

The old WinInstall 2003 LE that came with Windows 2000 Server does a fairly decent job generating these kinds of snapshots for reference purposes, but the MSIs it generates are abysmal. (I gave up using it and have started just doing snapshots myself "by hand" as I've described above.)
Comment: I just removed my previous comment - which contained a broken link to **Scalable Smart Packager CE** (appears discontinued). **For repackaging software / tools**, perhaps see **Stefan Kruger's comprehensive list** at [**installsite.org**](http://www.installsite.org/pages/en/tt_corp.htm). Hard to keep up with all these tools that are useful but end up deprecated.
Answer: Sysinternal's Process monitor might come in handy here.  Though it could be a bit too verbose, you can filter out other processes and tweak until it works best for you.  Launch it and scan, then start your install and stop once it's done.
Process Monitor
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
There might be other Free solutions that are specific for the launched binary install, but I'm not aware of them.
Quick Update
I agree with Evan, at least for the registry, if it's too verbose you might want to run an export before and after the install.  Windows 2003 Support tools come with windiff.exe (an old favorite for looking up differences in the registry - between two .reg files).
Answer: Check out Total Uninstall
It will watch from before and after an install and tell you exactly what that program did.
http://www.martau.com/tu_download.php
Answer: You can use Installshield product to open the package, and so you will know what it will do without having to install it for real. This product also integrates a capture tool to do a snapshot before/after


Appropriate Architecture of Asynchronous Tests with React Testing Library to avoid hanging tests

Question: Am trying to run asynchronous tests for a React page which uses mock api data but they are hanging for as long as you set the Jest timeout to. Am using mock service worker (msw) to provide the page data which is working fine in dev, and Redux.   Am following the recommendation from the Redux team of not mocking Redux so that you can do proper integration testing and see how the page actually runs. A Redux action calls the fetch which is then populated by msw and the data is then populated in the Redux store. However the test always times out on the await WaitFor.
test('displays position page', async () => {
    const container = document.createElement('div');
    const root = createRoot(container!);
    root.render(
    <ReduxProvider store={store} key="redux">
        <MemoryRouter initialEntries={['/']}>
            <PositionPage />
        </MemoryRouter>
    </ReduxProvider>
    )
  await waitFor(async () => {
    expect(await screen.getByText("XXXX", { exact: false })).toBeInTheDocument();
  })
});

For msw I have setupTests.ts
import '@testing-library/jest-dom';
import { getServer } from './core/mocks/server';

const server = getServer();
beforeAll(() => {
  server.listen()
});
afterEach(() => {
  server.resetHandlers()
})
afterAll(() => {
  server.close()
})

and in server.ts:
import { setupServer } from 'msw/node';
import type { SetupServer } from 'msw/node';
import { handlers } from './handlers';

// eslint-disable-next-line @typescript-eslint/init-declarations
let server: SetupServer | undefined;
export const getServer = (): SetupServer => {
  if (!server) {
    server = setupServer(...handlers);
  }
  return server;
};

What am I doing wrong here?  Is it because Redux is the real Redux here rather than being mocked? Is there a way to get this to work without having to lose all the "real world" testing elements that using proper Redux gives you?
Answer: Bit of a shot in the dark, but are you using fakeTimers? You can also have set them in the jest.config.js:
const config = {
  fakeTimers: {
    enableGlobally: true,
  },
};

They don't always work well with async/await tests. And you would get the behaviour you are describing.
Otherwise it might be helpful to also share the code under test, i.e. your PositionPage.
Update
Waitfor doesn't need to contain an async function. probably not what is causing the issue. But screen.getByText("XXXX", { exact: false })).toBeInTheDocument(); doesn't return a promise, so you shouldn't await it:
  await waitFor(() => {
    expect(screen.getByText("XXXX", { exact: false
  })).toBeInTheDocument();
  })

What are you using for store? it should be the same as your actual store, but you should create a new instance for every test. I do this by exporting my createStore function from store.ts
Comment: No fake timers, no.  Agree that would definitely be an issue.  Ok I'll add the other code you suggest, thanks


Finding transformation $\mathbf{A}$ which minimizes $\sum_t \lVert \mathbf{x}(t) - \mathbf{Ay}(t) \rVert^2$

Question: Let's say, I have a bunch of measurement vectors $\mathbf{x}(t)$ and $\mathbf{y}(t)$ for times $\{t_1,t_2...t_n\}$ and would like to compute the matrix A s.t.
$$A =\underset{A}{\operatorname{argmin}} \sum_{t} \lVert \mathbf{x}(t) - \mathbf{A}\mathbf{y}(t) \rVert ^ 2$$
Let, $\mathbf{x}(t)$ be the $t^{th}$ column of a the matrix $\mathbf{X}$ and $\mathbf{y}(t)$ be the $t^{th}$ column of a the matrix $\mathbf{Y}$
My initial intuition/approach was that $\mathbf{A}$ should be a projection matrix that projects the columns of $\mathbf{Y}$ to the column space of $\mathbf{X}$, which would minimize the expression above. This gives me $\mathbf{A} = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}$.After some thinking, I've come up with a few counter examples to convince myself that the above solution does not result in the global minimum.
However, in this paper [1], appendix A2, $\mathbf{A} = \mathbf{X}\mathbf{Y}^{\top}(\mathbf{Y}\mathbf{Y}^{\top})^{-1}$ seems to be their solution.
Is there something trivial I am missing? How does one derive the expression from paper [1] above?
[1] Parra, Lucas C., et al. "Recipes for the linear analysis of EEG." Neuroimage 28.2 (2005): 326-341.
Answer: Given matrices $\mathrm A$ and $\mathrm B$, both with $n$ columns, we would like to find matrix $\mathrm X$ such that
$$\| \mathrm X \mathrm A - \mathrm B \|_{\text{F}}^2$$
is minimized. Differentiating the cost function with respect to $\mathrm X$ and finding where the derivative vanishes, we obtain the following linear matrix equation
$$\mathrm X \mathrm A \mathrm A^{\top} = \mathrm B \mathrm A^{\top}$$
If $\mathrm A$ has full row rank, then $\mathrm A \mathrm A^{\top}$ is invertible and the linear matrix equation has the unique solution
$$\hat{\mathrm X} := \mathrm B \mathrm A^{\top} (\mathrm A \mathrm A^{\top})^{-1}$$
Answer: Thank you both @Rodrigo de Azevedo and @Stefan Jorgensen. Here is my solution based on solution by @Rodrigo de Azevedo:
Turns out the Frobenius Norm of a matrix $A$ is equal to the square root of the matrix trace of $AA^H$ [1]. If $A$ is a real matrix:
$$\lVert A \rVert_{F} = \sqrt{AA^H} = \sqrt{AA^{\top}} $$
So,
$$\underset{A}{\operatorname{argmin}} \sum_{t} \lVert \mathbf{x}(t) - \mathbf{A}\mathbf{y}(t) \rVert ^ 2 = \underset{A}{\operatorname{argmin}}  \lVert \mathbf{X} - \mathbf{A}\mathbf{Y} \rVert _{F}^{2} = \underset{A}{\operatorname{argmin}}  \DeclareMathOperator{\Tr}{Tr}[( \mathbf{X} - \mathbf{A}\mathbf{Y})(\mathbf{X} - \mathbf{A}\mathbf{Y})^{\top}]$$
From here we can take the derivative of the above objective function w.r.t. A, we can use the Eq. 119 from the matrix cookbook [2].
$$\frac{\partial}{\partial \mathbf{A}}\Tr[(\mathbf{AXB}+\mathbf{C})(\mathbf{AXB}+\mathbf{C})^{\top}] = 2\mathbf{A^{\top}}(\mathbf{AXB}+\mathbf{C})\mathbf{B^{\top}}$$
By substituting:
$$\mathbf{I \rightarrow A, -A \rightarrow X, Y \rightarrow B, X \rightarrow C}$$
We Get:
$$\frac{\partial}{\partial \mathbf{A}} \Tr[( \mathbf{X} - \mathbf{A}\mathbf{Y})(\mathbf{X} - \mathbf{A}\mathbf{Y})^{\top}] = \mathbf{0}$$
$$2 \mathbf{I}^{\top}(\mathbf{I}(\mathbf{-A})\mathbf{Y} + \mathbf{X})\mathbf{Y}^{\top} = \mathbf{0}$$
$$\mathbf{A}= \mathbf{XY}^{\top}(\mathbf{YY}^{\top})^{-1}$$

[1] http://mathworld.wolfram.com/FrobeniusNorm.html
[2] http://www2.imm.dtu.dk/pubdb/views/edoc_download.php/3274/pdf/imm3274.pdf
Comment: Sorry about that! Fixed.


Problema ao passar Bean polulada para controller e inserir no BD utilizando Java com Spring mvc

Question: Gostaria que pudessem me ajudar com esse problema que está ocorrendo na minha aplicação.
Segue abaixo o codigo:
 package br.com.estoque.Controller;

 import java.util.Map;

 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.ui.ModelMap;
 import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import br.com.estoque.Dao.CategoriaProdutoDao;
import br.com.estoque.Dao.ProdutoDao;
import br.com.estoque.Modelo.Produto;

@Controller
public class ProdutoController {

@RequestMapping("produtoForm")
public ModelAndView entradaForm(){
    ModelAndView mav = new ModelAndView();
    CategoriaProdutoDao dao = new CategoriaProdutoDao();
    mav.setViewName("produtos/frmCadastroProduto");
    mav.addObject("lista",dao.listar());
    mav.addObject("produto",new Produto());
    return mav;

}

@RequestMapping(value = "/inserirProduto", method = RequestMethod.POST)
public String save(@ModelAttribute("produto") Produto produto){
    ProdutoDao dao = new ProdutoDao();
    dao.adiciona(produto);
    return "produtos/frmCadastroProduto";
}

}

Minha frmCadastroProduto
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>

        <form:form action="inserirProduto" method="post" modelAttribute="produto">

        <form:label path="descricao">Nome Produto</form:label>
        <form:input path="descricao" />

        <form:label path="categoriaProduto">Selecione a categoria de produto</form:label>
        <form:select path="categoriaProduto">
            <form:option value=" - " label="--Please Select"></form:option>
            <form:options items="${lista}" itemValue="cdCategoriaProduto" itemLabel="descricao"/>
        </form:select>

                    <input type="submit" value="Register" />

        </form:form>

Tela de erro que está me voltando...
Comment: Luiz, bem-vindo ao [pt.so]! Qual é a URL do erro 400?
Comment: http://localhost:8080/Estoque/inserirProduto  é essa aqui!, se precisar de mais detalhes pra entender o problema eu mando!!
Comment: Comparei com um sistema que tenho aqui e aparentemente está tudo certo, exceto que não posso verificar suas configurações. Chega a executar o método `inserirProduto()`? Se passar por ali, provavelmente o problema está no redirecionamento ao final. Você tme um tiles configurado para `ok`?
Comment: E remova essa anotação `@ResponseBody`, ela é geralmente usada para retornar Json. Você tem outro cadastro que funciona com `POST`?
Comment: eu ja removi `@ResponseBody` , eu possuo sim uma JSP chamada ok . o Metodo adiciona() não chega a ser executado, pois nao me retorna uma msg no console que coloquei na execução do metodo.  Se precisar de mais informações a respeito das minhas configurações eu posso postar aqui!!! eu estou meio desesperado pois preciso entregar esse sistema até o final do ano, e essa é só a primeira tela de cadastro... obrigado pela ajuda!!!
Comment: se voce puder me passar como o controller deste seu sistema que vc comparou ficou, seria de grande ajuda tb!
Answer: O problema parece ser causado porque você tem um tipo "complexo" CategoriaProduto como atributo de Produtosendo mapeado para um campo de valor simples, i.e., a"combo" cujo valor das opções é baseado cdCategoriaProduto.
Subentendi isso pelo trecho produto.getCategoriaProduto().getCdCategoriaProduto().
A não ser que tenha feito a configuração de um binder em algum outro lugar, o Spring vai ver que a informação submetida na requisição não é compatível com o seu model recebido por parâmetro, explicando então o erro 400 de que a requisição está sintaticamente incorreta.
Qual a solução?
1. Use um atributo "Simples"
Crie um atributo codigoCategoria do tipo String ou numérico para receber o valor do formulário ao invés de usar uma classe sua.
Se precisar recuperar outras informações da categoria, use o código para recuperar o valor da sessão ou do banco de dados.
2. Crie um Editor
O Spring permite configurar uma classe especial para fazer a conversão automática durante o binding do request com o seu model.
Veja um exemplo (que peguei do SOen):
public class GroupEditor extends PropertyEditorSupport{

    private final GroupService groupService;

    public GroupEditor(GroupService groupService){
        this.groupService= groupService;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
      Group group = groupService.getById(Integer.parseInt(text));
      setValue(group);
    }
}

O método setAsText é usado durante o request. Ele vai receber o valor do campo (o código, no seu caso) e então você deve recuperar o objeto CategoriaProduto correspondente.
Note que esse groupService do exemplo seria um bean responsável por buscar o valor no banco de dados, por exemplo.
Finalmente, você configura o Spring para usar a classe acima no seu Controller da seguinte forma:
@InitBinder
protected void initBinder(WebDataBinder binder)     {
      binder.registerCustomEditor(Group.class, new GroupEditor(groupService));
}

Faça uma adaptação desse código para as suas classes.
Comment: Consegui criar a classe editora!! resolvi este problema Obrigadoo!
Comment: Sera que voce poderia me explicar melhor a opção numero 1 de como resolver o problema... eu alterei o meu controller em relação a como estou desponibilizando os meus models para a JSP, porem eu não entendi onde devo criar a variavel string para que não ocorra o erro. Obrigado utluiz
Comment: @LuizFernandoAugusto Mude o tipo do atributo de `CategoriaProduto` para uma `String`. Aí o Spring vai conseguir preencher o código. Aí se vc precisar de outros dados do produto, pode recuperar novamente do banco. Esta é a solução mais simples de fazer e explicar.
Answer: Este é o seu metodo
@RequestMapping(value = "/inserirProduto", method = RequestMethod.POST)
public String save(@ModelAttribute("produto") Produto produto){
//sua logica aqui
}

Note que você está enviado via post, então deveria ser assim:
@RequestMapping(value = {"/inserirProduto,""}, method = RequestMethod.POST)
public String save(@RequestBody Produto produto){
// sua logica aqu
}

Quando vem da tela o spring popular para você, como você esta usando post então tem que usar @RequestBody, note também o uso das {} no @RequestMapping.
Assim vai funcionar corretamente.


What's the intuition behind the Co-Area formula?

Question: I mainly work in statistics and I know only basic measure theory. I was trying to understand the Co-Area formula by Federer.

If $f:\mathbb{R}^M\to \mathbb{R}^N$ is a Lipschitz function with $M \geq N$ then
$$
\int_A J_N f(x) d\mathcal{L}^M x = \int_{R^N} \mathcal{H}^{M-N} (A\cap f^{-1}(y)) d\mathcal{L}^N y
$$

Could anyone please give me an intuition of what the formula implies and what it means practically? In particular, this is a simple example I am trying to wrap my head around: suppose we are in 2 dimensions and there is a curve defined by a function

What does the co-area formula tell us in this context?
Here are some practical questions:

My understanding is that we have some space of dimension $M$ and there a manifold in it of dimension $M-N$ and we would like to compute the area of this manifold using the Hausdorff measure. Is this what is happening?
I am completely lost as to why we need $A\cap f^{-1}(y))$ what's the intuition behind this?
On the right hand side we have $\mathcal{H}^{M-N}$. I am familiar with the Lebesgue measure $d\lambda$ however I am lost as to why we seem to have both the Lebesgue and the Hausdorff measure on the right hand side. I thought we should only have the Hausdorff measure on the RHS?
Comment: Can you add more detail so that I may not need to purchase a book to understand the question?
Comment: If you have Lebesgue measure on the plane, how will you use just that to talk about length of a curve in the plane? Think about slicing a region into curves and trying to compute the area of the region from information about the curves.
Comment: It is a generalization of say, integration using spherical shells - i.e. the volume of a balls is an integral over a one parameter family of spheres, with an appropriate choice of measure when integrating the spheres ($n-1$ dimensional Lebesgue measure, or Hausdorff measure, if your object for example has some kind of fractal structure). The formula is trivial when integrating smooth functions, but the formulation for Lipschitz functions is a bit more subtle, and requires some knowledge of the technical details of geometric measure theory.
Comment: Reading recommendations: especially if you're a beginner, Federer's book is very hard to follow, I'd rather recommend Geometry of Sets and Measures in Euclidean Spaces by Mattila and Measure Theory and Fine Properties of Functions by Evans-Gariepy.
Comment: @leslietownes apologies, I published the question too early! I just added some questions. I will try to formulate them more concretely.
Comment: As already pointed out, coarea formula is a generalization of Fubini's theorem. Fubini tells us how to integrate over $\mathbb{R}^{M}$ by integrating over slices $\{ x \} \times \mathbb{R}^{M-N}$, and then over all $x \in \mathbb{R}^N$. Similarly, coarea formula shows how to do it with non-flat slices (given as level sets of $f$).
Comment: @rubikscube09 I added a very hand-wavey plot that I am using to try and understand what is going on in the co-area formula. Essentially I am interested in understanding what the Co-Area formula is telling me when I consider, say a 2D space $(X, Y)$ on which there is a 1D manifold described by some function $\{(x, y)\in X\times Y\, : F(x, y) = a\}$ where $a$ is a known constant. This is just a simple example.
Comment: @TedShifrin Thank you! Do you mind explaining what the terms in the integral are trying to express? For instance, on the LHS we have an integral over a measurable set $A$. The integral is done wrt the $M$ dimensional Lebesgue measure, which is fine. This is the integral of the Absolute Determinant Jacobian of a function, so I'm assuming there is a transformation involved?
Comment: @Euler_Salter yes, this is due to the change of variables: https://en.wikipedia.org/wiki/Integration_by_substitution - see the multivariate portion.
Comment: @rubikscube09 Thanks! I understand the change of variables formula but what I don't understand is why it's been used. What does the LHS mean practically? What's the role of $f$?
Answer: This is most easily understood when $N = 1$. Suppose $A \subset \mathbb{R}^m$ is a bounded domain and $f: A \rightarrow \mathbb{R}$ is a smooth function whose gradient is everywhere nonzero.
Its level sets are non-intersecting hypersurfaces. Suppose first that you want to compute the volume of the $A$ in terms of the surface areas of the hypersurfaces. Suppose $a$ is the inf of $f$ on $A$ and $b$ is the sup. You can divide the interval $[a,b]$ into equal sized subintervals $I_1 = [t_0,t_1], \dots, I_N = [t_{N-1},t_N]$ of size $\delta = (b-a)/N$. The volume of $A$ is the sum of the volumes of $f^{-1}(I_k)$. On the other hand, each $f^{-1}(I_k)$ is a shell with varying thickness. At each point, the thickness is roughly $\Delta t/|\nabla f|$. So the volume of the shell is roughly
$$
V(f^{-1}(I_k)) \simeq \Delta t\int_{f^{-1}(t_k)}\frac{dA}{|\nabla f|},
$$
where $dA$ is the $(M-1)$-dimensional Hausdorff measure on $f^{-1}(t_k)$.
Adding up the volumes of the shells and taking the limit $N \rightarrow \infty$, we see that the volume of $A$ is
$$
V(A) = \int_{-\infty}^{\infty} \int_{f^{-1}(t)} \frac{dA_t}{|\nabla f|}\,dt,
$$
where $dA_t$ is the $(M-1)$-dimensional Hausdorff measure of $f^{-1}(t)$.
If, on the other hand, you integrate $|\nabla f|$ on $A$ using the same approach, you get
$$
\int_{f^{-1}(I_k)} |\nabla f|\,dx \simeq \Delta t\int_{f^{-1}(t_k)}|\nabla f|\frac{dA}{|\nabla f|},
$$
and therefore
$$
\int_A |\nabla f|\,dx = \int_{-\infty}^{\infty} \int_{f^{-1}(t)}\,dA_t\,dt
$$
The $N>1$ case is similar, except you chop $\mathbb{R}^N$ into small rectangular pieces and use the fact that the cross section of the inverse image of each piece is roughly a parallelogram whose volume is $(J_Nf)^{-1}$.
and therefore
$$
\int_A J_Nf\,dx = \int_{\mathbb{R}^N} \int_{f^{-1}(y)}\,dA_y\,dy,
$$
where $dA_y$ is the $(M-N)$-dimensional Hausdorff measure on $f^{-1}(y)$.
The general formula is
$$
\int_A \phi(x)\,dx = \int_{\mathbb{R}^N} \int_{f^{-1}(y)} \phi(x)\frac{dA_y}{J_Nf}\,dy
$$
Comment: Hello, I wonder if you could elaborate on the "At each point, the thickness is roughly $\Delta t/|\nabla f|$. How do you derive this?
Comment: @user57, the 1d version is: Given $y = f(x)$, the change in $y$ is approximately $f'$ times the change in $x$. Therefore, the change in $x$ is roughly the change in $y$ divided by $f'$.
Answer: First, it follows from approximation by characteristic functions that the formula in the OP generalizes to
$$
\int_{R^M} u(x) J_N(Df(x)) \, d\mathcal{L}^{M} = \int_{R^N} \Big(\int_{f^{-1}(z)}u\, d\mathcal{H}^{M-N}\Big)d\mathcal{L}^N(z)\, ,
$$
for every measurable $u\colon R^M \to [0,+\infty]$ . It is part of the claim that the different components are measurable and that the integrals are meaningful.
This means that to integrate a function $u$ we may first integrate along fibers coming from the function $f$. The most familiar example of this is the Fubini's theorem: If you take $f(x_1,\cdots,x_M) = (x_1,\cdots,x_N)$.
The next example is integration in spherical coordinates: take $f:R^M \to R^1$ be $f(x)=|x|$.
So, that must be a good start for intuition.
Important delicate issues:

Even for smooth $f$ we cannot guarantee that all fibers $f^{-1}(z)$ will be manifolds (let alone of dimension $M-N$). Example: $f(x,y)=x^2-y^2$, and level set of zero. In Lipschitz case, you can draw any shape and let $f(x)$ be distance of $x$ to that set. Obviously, $f$ is Lipschitz and level set of zero is the shape you started with. The reason coarea formula survives this is that if $f$ is Lipschitz, then for a.e. $z$ the sets $f^{-1}(z)$ will be countably $\mathcal{H}^{M-N}$-rectifiable and integration against Hausdorff measure will be meaningful.

Integrability of $z \to \mathcal{H}^{M-N}(f^{-1}(z)\cap A)$ is not easy! It requires the so-called coarea inequality.

The coarea formula is not obvious even for sets $A$ of measure zero!

There is a proof of the coarea formula that uses the implicit function theorem to "straighten" the fibers so that the proof reduces to Fubini's theorem.

Pictorially, if $U$ is a (measurable) set in $R^M$ (here in my picture $R^2$) then $F^{-1}(z)$ (here sample $z=a_1,a_2,\cdots$ drawn) "foliate" $U$. The coarea formula says that integration over $U$ can be done first by integration along these fibers/level sets.


Show $\sin\left(2\pi\sqrt{n^2+(-1)^{n}} \right)=\frac{(-1)^{n}\pi}{n}+\mathcal{O}\left( \frac{1}{n^2}\right) $

Question: I would like to prove the following:
$$\sin\left(2\pi\sqrt{n^2+(-1)^{n}} \right)=\dfrac{(-1)^{n}\pi}{n}+\mathcal{O}\left( \dfrac{1}{n^2}\right). $$
My attempt:
\begin{align*}
\sin\left(2\pi\sqrt{n^2+(-1)^{n}} \right)&=\sin\left(2\pi\sqrt{n^2\left(1+\dfrac{(-1)^{n}}{n^2}\right)} \right) \\
&= \sin\left(2\pi\ n\left(1+\dfrac{(-1)^{n}}{n^2}\right)^{\dfrac{1}{2}} \right)  \\
&=\sin\left(2\pi\ n\left(1+\dfrac{(-1)^{n}}{2n^2}+\mathcal{O}\left( \dfrac{1}{n^{4}}\right)\right) \right) \\
&=\sin\left(2\pi\ n+\dfrac{(-1)^{n}\pi}{n}+\mathcal{O}\left( \dfrac{1}{n^{3}}\right)\right)  \\
&=(-1)^{2n}\sin\left(\dfrac{(-1)^{n}\pi}{n}+\mathcal{O}\left( \dfrac{1}{n^{3}}\right)\right)  \\
&=\dfrac{(-1)^{n}\pi}{n}+\mathcal{O}\left( \dfrac{1}{n^{3}}\right).  \\
\end{align*}
I got $\mathcal{O}\left( \dfrac{1}{n^{3}}\right) $ instead of $\mathcal{O}\left( \dfrac{1}{n^{2}}\right). $
  Is my proof correct?
Comment: Yes this is correct. Your answer is more accurate.
Comment: so they made a mistake ?
Comment: @Educ: You skipped some justifications at the last step, but it's not a mistake to give a correct statement even though a stronger statement holds. See my answer for details.
Answer: Yes, what you have is quite correct and is a more powerful statement than the one they provided. You skipped some details at the end. You in fact need to use $\sin x = x + O(x^3)$ at the last step, and I'm guessing that the original author used only $\sin x = x + O(x^2)$. One gets the stronger result here by using the second-order Taylor polynomial of $\sin$ at $0$.
Comment: In general, if one considers just the *first*-order Taylor polynomial for $\sin$, rather than second, one gets the $O(x^2)$ error estimate. ... I still say that if you're writing a careful explanation, you should include this observation as justification for the last step.
Comment: @Educ Since, as $x \to 0$, $O(x^3)=O(x^2)$ we can't say there is a mistake. As explained by Ted Shifrin above.
Comment: as i know $$\sin x = x +-\dfrac{x^{3}}{3}+o(x^3)\implies \sin x = x + O(x^3) $$ and where that come from $\sin x = x + O(x^2) $
Comment: but please could you tell me why the author always prefer order $2$


Total partition of a sequence

Question: From a sequence of size let say n consisting of numbers 1,2...n find the number of groups such that R and (R-1) will be in the same group if the sequence [1,2,3...N] is divided into group of "X" numbers sequentially i.e [1...N] is divided into groups [1...X],[(X+1)...2*X], [(2*X+1)...3*X] ... [ (X*floor((N-1)/X)+1)...N] , where 1<=X<=N and last group can have less than X numbers.
For eg: n=5 R=5
 For different values of "X" groups formed are as follow
For, X=1 ,
               [ {1},{2},{3},{4},{5} ]
<code>     X=2
           [ {1,2} , {3,4} , {5} ]

     X=3
           [ {1,2,3} , {4,5} ]

     X=4
           [ {1,2,3,4} , {5} ]

     X=5
           [ {1,2,3,4,5} ]
</code>
We can clearly see that for X=3 and X=5, R and R-1 are in same groups.Hence answer=2.
Example 2:n=6 R=5
   X=1
<code>           [ {1},{2},{3},{4},{5},{6} ]

     X=2

           [ {1,2} , {3,4} , {5,6} ]

     X=3

           [ {1,2,3} , {4,5,6} ]

     X=4

           [ {1,2,3,4} , {5,6} ]

     X=5

           [ {1,2,3,4,5}, {6} ]

     X=6

           [ {1,2,3,4,5,6} ]
</code>
here ans=3 for X=3,5 and 6.
Note:Can a formula be computed in general for this?
Answer: When X divides R-1 then R and R-1 will be in separate blocks.  Otherwise I do not understand what you are asking.
Comment: thank you for your answer.so we need to calculate divisors of r-1 and that will involve prime factorization!

Total partition of a sequence


Can't access import.io's new web extractor/dashboard

Question: I'm reading through this articles:

https://www.import.io/post/our-biggest-update-ever/
http://importio.desk.com/customer/en/portal/articles/2402346-import-io-product-list

First one says:

If you log into Import.io using a web browser you will see the new platform but if you log into Import.io using the desktop application you will see the old platform.

Well, no. If I log in with a browser I see the old platform.
Second article states:

My Data/Dashboard
  http://dash.import.io

This just renders a blank page.
Seems like I am not able to access the new platform?
I am authenticated via Github using Firefox 38.1.0.
EDIT:
Before you downvote:
https://www.import.io/help/community
SO is listed as an official community support channel
Answer: StackOverflow is a programming community. This question will be more suited to their facebook group (https://www.facebook.com/groups/333804556787487/567946190039988/) or their new forum (http://community.import.io/).
But it seems that the page is not compatible with Firefox 38.X. Right now we're only supporting the last version of Chrome, Firefox and Safari.
Comment: https://www.import.io/help/community/ SO is listed as an official community support channel
Comment: For technical questions, probably StackOverflow is not the audience you're trying to reach with that question!
Comment: It is a technical question.
Comment: Ok, verified. http://dash.import.io is not working right now for FF 38.X, but it is working for the last stable version (FF46).


Getting CUPS and printing working on Ubuntu with Windows Subsystem for Linux

Question: I'm building a cross platform printing app and need to test it on various Linux. I could use VMs but I've got WSL just sitting here working and it will be a lot more convenient, at least initially just to use it.
I have installed CUPS but it won't run:
$ dpkg -s cups
Package: cups
Status: install ok installed
...
$ sudo systemctl restart cups.service
System has not been booted with systemd as init system (PID 1). Can't operate.

I found a single guide on the 'net for printing in WSL and it make it sound like it "just works": https://www.scivision.dev/scanningprinting-with-windows-subsystem-for-linux/
What am I missing?
Answer: Use sudo service cups start
or
sudo /etc/rc.d/init.d/cups start
systemctl is dependent on systemd as your error message says


Use nested static class as ActionListener for the Outer class

Question: I want to use an nested static class as an actionListener for the enclosing class's GUI elements.
I did something like this:
public class OuterClass {

    public static void myImplementation() {
        OuterClass.StartupHandler startupHandler = new OuterClass.StartupHandler();
        exitMenuItem.addActionListener(startupHandler); // error Line
    }

    public static class StartupHandler implements ActionListener {

   @Override
    public void actionPerformed(ActionEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");

        if (e.getSource() == exitMenuItem) {
            System.exit(1);
        } else if (e.getSource() == helpMenuItem) {
            // show help menu
        }
    }
}
}

But when I invoke this code I get the NullPointerException at the //error Line.
Is this the right method to do do this or there is something I did am missing?
Comment: Looks like `exitMenuItem` variable has `null` value when calling your `myImplementation` method. Use a debugger to fix this issue in your code.
Comment: I agree with @LuiggiMendoza There is no point in asking a question for `NullPointerException` get a debugger and debug it. You can use this knowledge in future also.Every day there are so many questions about `NPE`
Comment: @LuiggiMendoza: Aaahhh.... exitMEnuItem was not initialized. That was a silly mistake by me. I will take care of these things now on.Thanx
Answer: Is exitMenuItem being initialised? I bet it is null.
If you include more of the class (such as where you declared exitMenuItem) we'll pin point the problem more easily.
Comment: Thanx. exitMEnuItem was not initialized. That was just a silly mistake by me. Thanx again.


Can do unit test without TDD?

Question: I'm in a project where we don't do TDD, because our bosses and the cliente are very "old styled" people. Because I can't do design through TDD but I feel fear to changes, I would like to write unit tests for my own safety. But, how those unit test would be? Do I have to write a test for each method specification for test that they do what it's supposed they do? Do I have to test for each new functionality like TDD but without design? I have a mess in my mind.
Thanks in advance.
Answer: You probably can't hurt anything by doing unit tests - regardless of how well they're done - except for one possible side-effect, and that is false confidence.
We tend not to do hardcore TDD, nevertheless the unit test coverage ranges from non-existent to moderate depending on project, and is becoming increasingly valuable as the idea settles in.
For general pointers, I'd say the following are key priorities for you right now:

Test what you know to be important
Test what you know to be fragile
Write tests to expose any new bugs, then solve the bug by making modifications that pass the test
Apply TDD where possible to any new features
Acknowledge that you can't TDD an existing project. By its nature, TDD only applies to new ground, whether that's a new product, or a new feature for a legacy product. Don't let this fact dishearten you.
Answer: Yes. TDD is yet another software development technique which happens to utilize unit testing heavily. Unit testing as a process is fine on its own without TDD behind. Not to mention, sometimes it's not even possible to do TDD yet you do write tests (think legacy systems/existing untested code testing).
But as for what you should test. Depending how deep with testing you want (can) go, you can start with end user oriented functionality, through system components testing (ie. class contracts) up to simply assuring your code does what you claim it does - that's pretty much the final, most fine-grained unit test which you'll most likely have a lot of.
In general, what to test is not an easy question, I've happened to answer several variants of that question already, to give you few tips:

test what your code does, not what it does not
if you got certain requirement, have a test covering it
test single feature at time
focus on public contract, skip private bits

Also, reading few of the top voted unit testing questions might give you some ideas on why you will benefit from testing, regardless of using TDD or not.
Answer: When you say "we don't do TDD", do you mean that others don't practise TDD or that your bosses forbid you from practising TDD? If it's the first one, then you can practise TDD as much as you want, as long as you don't try to force other people to do it. If it's the other one, then tell your bosses that they pay you to write code the best way you know how, and TDD is part of how you do that.
You can certainly write tests without practising TDD. People do it all the time. Use the old saying, "Test until fear turns to boredom". Write tests for whatever you fear might not work correctly.

Can do unit test without TDD?


How to work out the WMI Class name from its perfmon counter name

Question: So I have been provided with a bunch of performance counters that are housed within a particular performance object (i.e. these are not one of the default perf counters that come with Windows) and because I need to access these statistics on a remote machine, I have to use WMI to achieve this.
However, I can't work out which WMI class this particular performance object relates to (I've looked through the list of Win32_PerfRawData_* classes but there isn't anything that looks like it relates to the performance object in question at least by name).
My questions:

Can a performance counter exist without a backing WMI class?
How do I work out which WMI class I should query to get the perf stats I need?
Answer: Sometimes WMI classes may not appear automatically as they should. If you execute 'wmiadap /f' in the command prompt it will reparse all performance libraries on the system (you'll be able to see new libraries after system restart).
In a meanwhile performance counter you are looking for is one of the standard you may want to take a look at Performance Counter Classes list.
Answer: WMI doesn't automatically map each performance object and it's counters. You need a specific WMI provider or atleast a MOF-file describing the classes.