c - undefined behavior when changing element of char array

Question: Line 9 of the below code generates undefined behavior. Is this due to the fact that title1[] is outside of main() and is global? Or is it because something else that I'm missing?
1. char title1[]="The Name of the Rose";
2. Book book1={title1,900,0};
3. int main(){
4.   Book book2={"Foucault's Pendulum",1000,0};
5.   Book* book3=(Book*)malloc(sizeof(Book));
6.   *book3=book2;
7.   book1.next=&book2;
8.   book2.next=book3;
9.   book1.title[0]='B';
10.  book2.title[0]='A';
11.  {
12.    Book list[2];
13.    list[0]=book1;
14.    list[1]=book2;
15.    list[1].next->next=&book2;
16.    {
17.      Book* p=&list[0];
18.      while (p!=0) {
19.        p=p->next;
20.    }
21.  }
22. return 0;
23.}

EDIT:
Added the Book definition:
;struct Book
typedef struct Book {
;  char* title
  int pages;
;  struct Book* next
;} Book

Comment: It's undefined because you're modifying a string literal constant (not a copy of it).
Comment: @JanDvorak Are you sure?  `book1.title` is a reference to the character array `title1`, so unless the `title` element of the `Book` class is const-qualified (in which case, the code should not compile), there shouldn't be a problem.  Now, line 10 and assigning to `book2.title` which is a reference to a string literal; that would be undefined behaviour.  And this is C; C does not have 'constructors'.
Comment: Could you add the definition of the `Book` class?
Comment: I'm fairly sure that the line with the UB is actually line 10, which modifies the string in the second book, not the first entry - which is perfectly allowed to do. Probably just a counting error on line numbers, I expect.
Comment: How do you know that line 9 gives undefined behavior?
Comment: is the first element in the book structure is a pointer ?
Comment: @PhilipKendall Apparently, its first element is a pointer to char and that's all you need to know about it.
Comment: Duplicate hundreds of times over.  [Modifying String Literal](http://stackoverflow.com/questions/5464183/modifying-string-literal) is just one example.
Comment: Please try to create an [SSCCE](http://sscce.org) before posting.  It'll help you find and fix your bugs without having to ask duplicate questions here.
Comment: @PhilipKendall added definition.
Comment: ...For that matter, what UB are you observing?  How can you call it UB without knowing that what you're doing is wrong, or else observing a variety of strange behaviors that you're attributing to UB?
Comment: @DavidGrayson it was the TA answer to this question. phonetagger sometimes i get seg fault, other times it runs for ever
Answer: No, line 9 is not undefined behavior. It writes to this array:
char title1[]="The Name of the Rose";

which is not a string literal (but initialized by one). Such a plain array can be modified to your liking. It would have been different if you would have declared it like this:
char *title1="The Name of the Rose";

The undefined behavior is in line 10, here you are writing into a string literal, which is not allowed.
BTW, when asking a question here, please cook it down to a minimal example that shows your point. Most of the code you posted is completely useless for your question.
Comment: So it's fine to change elements of an array that resides in the global code? Isn't this memory read only?
Comment: Why should it be read-only? It would only be read-only if you'd declare it with a `const`-qualifier. String *literals* are different from that, they aren't objects that you are supposed to change.
Comment: I think one should even say "they are objects you are **not** supposed to change".
Comment: @Daniel, yes, should have said that.
Answer: You are trying to modify a string literal in line 10.
Comment: `char title1[]` is an array so i'm not trying to modify a string literal
Comment: @Tom It's line 10 that invokes UB through attempting to modify a string literal, as Jonathan Leffler pointed out.
Answer: The error occurs on line 10, because a string literal is a constant and therefore read only. Any write on it will cause an error.


Make a custom view mode default

Question: I made a custom view mode in Display Suite and I would like to use it as the default view mode for a given content type. Can anybody enlighten me as to how to do it?
Answer: This is the way i set the 'fullpage' view_mode of a node as default:
<code><?php
/**
 * Implements hook_entity_view_mode_alter().
 */
function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // Set default view mode.
  if (isset($context['entity']->nid)) {
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'YOUR_CTYPE' && $view_mode == 'full') {
      $view_mode = 'fullpage';
    }
  }
}
</code>
It actually sets the view_mode to 'fullpage' when in full mode (default), but you could ommit that part (&& $view_mode == 'full').
Remember that 'fullpage' is the machine name of my view_mode and 'YOUR_CTYPE' is the machine name of your content type.
Not sure if this will work with Display suite though...
Comment: Great, there was no particular reason this won't work with DS, just never used it.Glad it helped.
Comment: DS is for Display Suite - i just edited the original question and I'll try your suggesion
Comment: Yes it does!
Just for the record:
I created a custom module in sites/all/modules/custom/, created an .info and a .module file, to which I pasted the code above, replacing the module name with the one I chose and YOUR_CTYPE with the *machine name* of the content type (I emphasize that because i first just typed the human name and it obviously did not work). Thanks!
Comment: And it seems to work consistently with Display Suite, i can change the default view mode in code to some new one created in DS.

Make a custom view mode default


Random movement with turtle

Question: I want it to take the current x and y coordinates and pick either x ± 10 or y ± 10 and go there, but i keep getting TypeError: turtle.Vec2D() argument after * must be an iterable, not float
This my the code:
from turtle import Screen
import turtle, random, time
turtle.speed(1)
goto = [
    turtle.xcor() + 10,
    turtle.xcor() - 10,
    turtle.ycor() + 10,
    turtle.ycor() - 10
]
turtle.goto(goto[random.randint(0,3)])

Answer: The problem is exactly what the error message says. You are passing a number when you are supposed to pass a pair of coordinates or a Vec2D. From the goto documentation:

Parameters
x – a number or a pair/vector of numbers>
y – a number or None
If y is None, x must be a pair of coordinates or a Vec2D (e.g. as
returned by pos()).

Currently you are only passing x, since all the values in your goto array are numbers. Therefore, y is the default value None.
Here is a fixed version:
nextPos = [
    (turtle.xcor() + 10, turtle.ycor()),
    (turtle.xcor() - 10, turtle.ycor()),
    (turtle.xcor(), turtle.ycor() + 10),
    (turtle.xcor(), turtle.ycor() - 10)
]

turtle.goto(nextPos[random.randint(0,3)])

[Try it out here]
(PS: I recomend renaming the array to make the code easier to understand)

Random movement with turtle


Contar frequência de ocorrências incluindo zeros

Question: Para o seguinte caso a contagem de x utilizando a função table irá retornar a frequência dos valores existentes. Gostaria de saber como retornar a contagem para o intervalo discreto de 1 a 12, incluindo os valores cuja frequência é zero.
set.seed(2)
x <- sample.int(12, 50, replace = TRUE)
table(x)

Answer: Para incluir os valores para os quais a frequência é zero, converta para factor com todos os níveis e aplique table.
table(factor(x, levels = 1:12))
#
# 1  2  3  4  5  6  7  8  9 10 11 12
# 6  6  5  3  3  8  5  5  5  0  2  2

O valor 10 tem uma frequência de zero mas está no resultado final, como pedido.
Comment: Esta solução atende o problema. Muito obrigado.
Answer: table usa a função tabulate, que retorna por padrão todos os intervalos. Pode usá-la diretamente:
set.seed(2)
x <- sample(12, 20, replace = TRUE)

table(x)
#> x
#>  1  2  3  5  6  7  9 10 11 12
#>  1  1  5  1  2  3  1  1  2  3

tabulate(x)
#>  [1] 1 1 5 0 1 2 3 0 1 1 2 3

Se precisa que retorne como um vetor nomeado:
setNames(tabulate(x), seq_len(max(x)))
#>  1  2  3  4  5  6  7  8  9 10 11 12
#>  1  1  5  0  1  2  3  0  1  1  2  3


Mysql Where ... In ... AND where ... in ... should only match on same index

Question: I have the query:
SELECT * FROM `users`
WHERE (`firstname` LIKE 'Luke' AND `lastname` LIKE 'Skywalker') OR
 (`firstname` LIKE 'Foo' AND `lastname` LIKE 'Bar') OR
(`firstname` LIKE 'Tom' AND `lastname` LIKE 'Turner');

But i would like to make it a bit more readable by using a where ... in ...
I tried
SELECT * FROM users
WHERE `firstname`
    IN ('Luke','Foo','Tom') AND `lastname` IN ('Skywalker','Bar','Turner');

But unfortunately this will also match "Tom Skywalker", "Foo Turner" and all mixes you can think off.
I have to select on first and lastname (perhaps more fields like DOB) since i am getting data from an external API and i have to check if those names are in our system.
Comment: What is the scale of data in your `users` table, and the number of rows from the external API that you will have to compare?  100's of rows?  50,000 rows?
Comment: I can get up to 1000 names back from the external API (I want to match facebook friends with users from my own database) my own database can get up to 10000 rows (it is currently in a testing fase, but i want to optimize all my sql query's at an early stage)
Answer: Using LIKE operator without wildcards doesn't make much sense. I think you should use =, particularly if you have to check if those names are in our system.
SELECT * FROM users
WHERE (firstname = 'Luke' AND lastname = 'Skywalker') OR
      (firstname = 'Foo' AND lastname = 'Bar') OR
      (firstname = 'Tom' AND lastname = 'Turner')

If you use an IN operator, as you said, will match different combinations. I think the previous example should be the fastest way to compare them.
Answer: SELECT *
FROM users
WHERE (firstname, lastname)
      IN ( ('Luke', 'Skywalker')
         , ('Foo' , 'Bar')
         , ('Tom' , 'Turner')
         )
;

Comment: @safarov: Valid in MySQL, Postgres and Oracle 11g. Not in Sql-Server.
Answer: You can combine them with concat:
WHERE concat(`firstname`,'-',`lastname`)
   IN ('Luke-Skywalker', 'Foo-Bar', 'Tom-Turner');

Comment: The problem with this solution is that it'll be quite slow
Comment: Good point.  I have added a clarification comment to the question.  If the dataset is small, I would prefer readability to performance.


porting from ios to windows

Question: I'm about to write code for Windows that has somewhat similar functionality to the one existing in already written application for iPhone. I'm thinking of separating common functionality to form a component and compile it to both to iPhone and to Windows. This code is written in Objective C and uses RestKit and Core Data (and probably sqlite). Is compiling it for Windows a viable task? As I understand it GCC could compile Objective C on Windows but I'm unsure about the RestKit and Core Data api availability on Windows. I have seen two names that could be of use: GNUStep and Cocotron but I don't know if they will play well together with RestKit.
Note: I have no idea about iOS development so I might be confusing things. Any help is appreciated.
Answer: You will not easily be able to share this functionality between your applications. CoreData uses a custom opaque (not documented) format for the sql store. You would be hard pressed to reverse engineer this.
You will probably save a lot of time by rewriting that part for windows, rather than trying to get it working. There really isn't much iOS code that can be reused under windows, unless you have written pure C or C++.

porting from ios to windows


TypeError: Cannot read property 'map' of undefined

Question: Não sei o pq ocorre esse erro:

TypeError: Cannot read property 'map' of undefined

Segue código:
var app = angular.module('Teste');
app.controller('testeController', ['$scope', '$http',
    function ($scope, $http) {

        $scope.formulario = {};
        $scope.isLoading = false;
        $scope.tipos = sema.tipoSimfiscal;
        $scope.municipios = sema.municipios;
        $scope.estados = sema.estados;
        $scope.categoriasProdutos = sema.categoriasProdutos;
        $scope.data = [];
        $scope.municipioDestinos = [];
        $scope.dTableOptions = {
            aoColumns: [
                { "sTitle": "Tipo" },
                { "sTitle": "Nº GF" },
                { "sTitle": "Nº DVPF" },
                { "sTitle": "Remetente" },
                { "sTitle": "Destinatário" },
                { "sTitle": "Situação" },
                { "sTitle": "" }
            ]
        };

        $scope.municipioDestinos = function (form) {
            $http.post('views/transparencia/sistemas/service.aspx/Consultar', {
                estado: form.estado || ''
            }).then(function (success) {
                let data = JSON.parse(success.data.d);
                $scope.data = data;
                $scope.isLoading = false;
                $scope.municipioDestinos = data;
            }, function (error) {
                $scope.isLoading = false;
            });
        };

        $scope.abrirModal = function (id) {
            let item = $scope.data.filter(function (it) { return it.Id == id })[0];
            let produtos = item.Produtos;
            if (item) {
                $('#lblTipo').text(item.Tipo);
                $('#lblNumeroGF').text(item.GfNumero);
                $('#lblNumeroDVPF').text(item.DvpfNumero);
                $('#lblRemetente').text(item.VendedorNome);
                $('#lblDestinatario').text(item.CompradorNome);
                $('#lblSituacao').text(item.SituacaoGfTexto);
                $('#lblClassificacao').text(item.Classificacao);
                $('#lblDataEmissao').text(item.EmissaoData);
                $('#lblConsumidorFinal').text(item.ConsumidorFinal);
                if (item.Exportacao == 0)
                    item.Exportacao = "";
                $('#lblExportacao').text(item.Exportacao);
                $('#lblEmbarque').text(item.Embarque);
                $('#lblCodigoBarras').text(item.CodigoDeBarra);
                $('#lblCpfCnpjVendedor').text(item.VendedorCpfCnpj);
                $('#lblCpfCnpjComprador').text(item.CompradorCpfCnpj);
                $('#lblMunicipioOrigem').text(item.VendedorMunicipio);
                $('#lblMunicipioDestino').text(item.MunicipioDestino);
                $('.tabelaProdutos tbody').html("");
                for (var i = 0; i < produtos.length; i++) {
                    $('.tabelaProdutos tbody').append("
" + produtos[i].Essencia + "	" + produtos[i].Classificacao + "	" + produtos[i].Quantidade + "	" + produtos[i].Produto + "	" + produtos[i].UnidadeMedida + "
 ");
                }
                $('#modalDados').modal().show();

            } else {
                alert('Item não encontrado');
            }
        };

        $scope.consultar = function (form) {

            if (!form.tipo) {
                alert('Informe o tipo de GF');
                return;
            }
            if (!form.status) {
                alert('Informe o Status');
                return;
            }
            if (!form.codigoDeBarras) {
                if (!form.periodo) {
                    alert('Informe o Período');
                    return;
                }
            }

            $scope.isLoading = true;

            $http.post('views/transparencia/sistemas/service.aspx/SISFLORA_ConsultarDadosGF', {
                municipio: form.municipio || '',
                municipioDestino: form.municipioDestino || '',
                tipo: form.tipo || 0,
                status: form.status || 0,
                codigoDeBarras: form.codigoDeBarras || '',
                numeroGF: form.numeroGF || 0,
                periodo: form.periodo || 0,
                categoria: form.categoria || 0,
                essencia: form.essencia || ''
            }).then(function (success) {
                let data = JSON.parse(success.data.d);
                $scope.data = data;
                $scope.isLoading = false;
                $scope.dTableOptions.aaData = data.Lista.map(it => {
                    return {
                        tipo: it.Tipo,
                        numeroGF: it.GfNumero,
                        numeroDVPF: it.DvpfNumero,
                        remetente: it.VendedorNome + ' / ' + it.VendedorCpfCnpj,
                        destinatario: it.CompradorNome + ' / ' + it.CompradorCpfCnpj,
                        situacao: it.SituacaoGfTexto,
                        download: `<button class="btn btn-default " onclick="angular.element(this).scope().abrirModal('${it.Id}');"><span class="glyphicon glyphicon-eye-open"></span></button></div>`

                    };
                });

            }, function (error) {
                $scope.isLoading = false;
            });
        };

        $scope.exportToJson = function () {
            sema.exportToJson($scope.dTableOptions.aaData, 'flores');
        };

        $scope.exportToCSV = function () {
            $(".buttons-csv").click();
        };
        $scope.exportToPDF = function () {
            $(".buttons-pdf").click();
        };
        $scope.exportToXLS = function () {
            $(".buttons-excel").click();
        };

    }]);

Comment: Bem, parece que na linha "$scope.dTableOptions.aaData = data.Lista.map(it => {", o atributo/Variavel 'Lista' não ta sendo declarado em nenhum lugar de seu código.
Veja se esta 'Lista' realmente existe, caso existe veja se possui valor, pois o erro está acusando que, o ".map" está tentando ser utilizado com algo indefinido.
Answer: O erro está na linha $scope.dTableOptions.aaData = data.Lista.map(it => {.
Provavelmente o atributo Lista, que é retornado da sua requisição, não não existe. O método map é uma propriedade de Arrays e só funcionará neles. Certifique-se de que a Lista exista e seja um Array.


To find that shape and length

Question: A circle of radius 'r' is centered at origin, consider an imaginary line y=r (tangent to the circle at 0,r say A)
Now what kind of shape should an arc (not necessarily circular) have that if initially it's one end is at A and being tangential to circle at A, then on rolling the arc over the circle (just like tyre rolls without sliding over road) the 'A' end of the arc always traces/'have locus on' y=r
Comment: Are you referring to a cycloid?
Comment: How can it be said, let's visualise it. If a smaller circle is inside and is touching a larger curve (like bigger circle for e.g.only) and the latter rolls over it such that the smaller circle is unmoved while the point of latter which was usually touching the smaller circle WILL TRACE some curve.  If that curve is along a line then what shape is that bigger curve.  Cycloid should come in picture in relative motion in circle and line, how is this case arising here!!
Comment: I am not sure what you mean by the "end" of the arc. Clearly as you roll down the circle the arc gets longer and longer. I am thinking some sort of spiral could remain always tangent to y = r.
Comment: @Victoria. Refer https://en.m.wikipedia.org/wiki/File:EpitrochoidOn3-generation.gif here if outer rolling circle would have been some other (could be non closed also) arc/shape but if on rolling, it traces a 'red' line like x=3 in that diagram. Then what is that curve? I wish I am understood!
Answer: Your question is not very clear at all.
In the differential geometry of curves, a roulette is a kind of curve that is described by a point (called the generator or pole) attached to a given curve and that curve rolls without slipping, along a second given curve that is fixed.
See https://en.wikipedia.org/wiki/Roulette_(curve)
We have :

cycloids, https://en.wikipedia.org/wiki/Cycloid
epicycloids, https://en.wikipedia.org/wiki/Epicycloid
hypocycloids, https://en.wikipedia.org/wiki/Hypocycloid
trochoids, https://en.wikipedia.org/wiki/Trochoid
involutes, https://en.wikipedia.org/wiki/Involute.

As you are working with "a circle of radius 'r' is centered at origin", we have to deal with epicycloids, hypocycloids or involutes.
Because of your english, I suspect you are referring to the involute.
But please, confirm.
Comment: Refer https://s7.postimg.org/4zpmr02az/Curve_Sliding_over_circle.jpg here the shape to be found is the red arc which although shown as a line segment but should be some different curve/'shape', but the condition to be satisfied is that one end of the arc (here 'A') should remain on y=r while the curve rolls over circle, like here A, A', A'' all remain on y=r
Comment: Please, correct me if I am wrong, in order to understand your problem. So we have a segment AB on line $y=r$. This segment rolls and translates in such a way that extreme A is always on line $y=r$, obtaining A', A'', ..... You want the curve made by B, B", B"", .... Is this correct?
Comment: Not the curve made by B but the AB curve itself such that this condition fulfills.
Comment: OK, I understand now. I will try to make something during the weekend. By the way, I think there are some meanings to make clear: https://en.wikipedia.org/wiki/Line_segment and https://en.wikipedia.org/wiki/Curve. Besides, with the motion described, point B traces a curve and segment AB defines an area.
Answer: After the comments mantained with Anshuman Dwivedi, I am posting a new answer.
**
I am solving the following problem:

A circle of radius $r$ is centered at origin.
Consider an imaginary line $y=r$, tangent to the circle at A = (0,r), and a segment AB of length $l$ on this line.
What shape will this segment describe if it moves rolling around the circumference and maintaining its point A on line $y=r$.

For any position of the segment around the circumference, we have:
We advance point A and rotate the segment till it is tangent to the circumference.
Coordinates of tangential point are calculated as follow
$Alfa= 2*atan((x-coordinate-of-point-A) / r)$
$Tx = r * cos( \pi/2- Alfa)$
$Ty = r * sin( \pi/2- Alfa)$
Now, new position of point B will be
$Bx = ( x-coordinate-of-point-A ) + l * cos(Alfa)$
$By = r - l*sin(Alfa)$
Following is the curve obtained
https://i.stack.imgur.com/QxRPJ.jpg
Comment: Dear cgiovanardi,
I think I am yet unsuccessful in conveying my question to the audience including you. Although I got a help from your references to 'the involute curve' here (https://en.m.wikipedia.org/wiki/File:Animated_involute_of_circle.gif)

Now, if a line segment is rolled over a circle, then their initial contact point traces an 'involute' then the problem is that.....

WHAT 'CURVE/SHAPE' SHOULD THE LINE SEGMENT BE REPLACED WITH, THAT IF THAT 'CURVE/SHAPE' IS ROLLED OVER THE CIRCLE IN A SIMILAR MANNER, THEN THE TRACE OF THE INITIAL CONTACT POINT BE ON A LINE?
Comment: @Anshuman Dwivedi: Sorry, but I don't understand your question.
Comment: Unless, I think the key word is "catenary". See if this is what you are looking for: https://www.macalester.edu/academics/mscs/documents/catenaries.pdf or http://web.mst.edu/~lmhall/Personal/RoadsWheels/RoadsWheels.pdf, figure 3.

To find that shape and length


Exact formulation of Paley-Zygmund inequality

Question: The Paley-Zygmund inequality states that $P(X \succ c\mathbb{E}[x]) \succ (1-c)^2 \frac{\mathbb{E}[X]^2}{\mathbb{E}[X^2]}$ for $X\succ 0$ and $0\prec c \prec 1$.
I've used $\succ$ here because I have seen this formula with pretty much any combination of $>$ and $\geq$ plugged in for the various instances of $\succ$.I guess for continuous random variables this sloppiness doesn't matter much in practice, but what is the exact formula here?
Comment: The [Wikipedia article](https://en.wikipedia.org/wiki/Paley%E2%80%93Zygmund_inequality) is clear on this.  Because it offers a proof, it also affords you the opportunity to check its accuracy.
Answer: Inside the probability function, if we allow equality, we increase the probability. Hence, the inequality is stronger if we do not allow equality there. Outside of the probability, the statement is strengthened if we allow equality. For the condition on $X$, we increase the strength of the statement if we allow equality. The same holds for $c$ (i.e., $0$ and $1$ should be allowed). So, we get the strongest statement if we state that for any $X\ge 0$ and $0\le c \le 1$,
$P(X > c \mathbb{E}[X]) \ge (1-c)^2 \frac{\mathbb{E}[X]^2}{\mathbb{E}[X^2]}$. And so one should use this form.
Having said this, the statement also requires $\mathbb{E}[X^2]>0$, or in the lower bound we get $0/0$, which has no meaning. Also, $c=1$ gives a vacuous statement, so it is not crucial to allow $c=1$ in the statement.


bound on the cardinality of the continuum? I hope not

Question: Suppose we don't believe the continuum hypothesis. Using Von Neumann cardinal  assignment (so I guess we believe well-ordering?), is there any "familiar" ordinal number $\alpha$ such that, for non-tautological reasons, $\aleph_\alpha$ is provably larger than the cardinality of the continuum? I would hope not since it would seem pretty silly if something like $\alpha = \omega_0$ worked and we could say "well gee we can't prove that $c = \aleph_1$, but it's definitely one of $\aleph_1, \aleph_2, \ldots , \aleph_{73}, \ldots$". I (obviously) don't know jack squat about set theory, so this is really just idle curiosity. If a more precise question is desired I guess I would have to make it

For any countable ordinal $\alpha$ is the statement: $c < \aleph_\alpha$ independent of ZFC in the same sense as the continuum hypothesis?

assuming that even makes sense. Thanks!
Answer: Mike: If you fix an ordinal $\alpha$, then it is consistent that ${\mathfrak c}>\aleph_\alpha$. More precisely, there is a (forcing) extension of the universe of sets with the same cardinals where the inequality holds.
If you begin with a model of GCH, then you can go to an extension where ${\mathfrak c}=\aleph_\alpha$ and no cardinals are changed, as long as $\alpha$ is not a limit ordinal of countable cofinality. For example, $\aleph_{\aleph_\omega}$ is not a valid size for the continuum. But it can be larger.
Here, the cofinality of the limit ordinal $\alpha$ is the smallest $\beta$ such that there is an unbounded function $f:\beta\to\alpha$. There is a result of König that says that $\kappa^\lambda>\kappa$ if $\lambda$ is the cofinality of $\kappa$. If $\kappa={\mathfrak c}$, this says that $\lambda>\omega=\aleph_0$, since ${\mathfrak c}=2^{\aleph_0}$ and $(2^{\aleph_0})^{\aleph_0}=2^{\aleph_0}$. Since $\aleph_{\aleph_\omega}$ has cofinality $\omega$, it cannot be ${\mathfrak c}$.
But this is the only restriction! The technique to prove this (forcing) was invented by Paul Cohen and literally transformed the field.
Comment: You could say that Paul Cohen forced a new outlook onto the world of set theory. :-)
Comment: Mike: The confusion here is that different 'versions' of ZFC can have different cardinals; for instance, you can't talk about 'the' $\omega_1$, but just the $\omega_1$ of your current model.  How can this be?  Well, think of $\omega_1$ as the set of all countable well-orderings; the word 'all' here is ill-defined, and it's possible for one model to know about countable well-orderings that another model doesn't. Saying that your extension has the same cardinals just means that you haven't introduced enough 'new' sets to change the cardinalities of old sets.
Comment: (cont) Likewise, the reason that $c$ can be equal to a given cardinal $\aleph_\alpha$ in one model and then larger (or smaller) than it in another is that the notion of 'the' set of all real numbers (or, if you prefer, all sets of integers) isn't necessarily well-defined, and again one model may know about sets of integers that another model doesn't.  This is essentially how Cohen's proof works, by creating a whole lot of (necessarily non-constructible) new sets of integers, enough to make $c$ necessarily greater than $\aleph_1$.
Comment: @Mike: I am identifying cardinals with ordinals, i.e., a cardinal $\kappa$ is a special set, and any other set has size $\kappa$ if it is in bijection with the set $\kappa$. That $\kappa\ne\kappa'$ means that there is no bijection between $\kappa$ and $\kappa'$. It is perhaps easier now to argue in terms of models: Suppose that $M$ is a model of set theory, and that, *in $M$*, there is no bijection between $\kappa$ and $\kappa'$. It may still be the case that there is such a bijection $f$, but it does not belong to $M$. (Continues)
Comment: (cont.) Suppose we can extend $M$ to a model $M[f]$ that now has this bijection $f$. Then, in $M[f]$, at least one of $\kappa$ and $\kappa'$ is no longer a cardinal, since we now have a bijection between it and a smaller ordinal. The method of forcing allows us, precisely, to extend a model $M$ to a larger model $M[f]$ for some appropriate $f$. What I meant by "same cardinals" is that in $M[f]$ an ordinal is a cardinal iff it was a cardinal in $M$, i.e., I have not added any bijections as in the example above. I guess I should say why this is relevant. (Cont.)
Comment: (cont.) The point is that I begin working on a model. Say, here ${\mathfrak c}=\omega_1$. I want to go to a model where ${\mathfrak c}\ge\omega_2$. For this, I add to $M$ a lot of reals that were not there before ($\omega_2$ of them), and form $M[f]$. If I don't do this carefully, in $M[f]$ I will have that ${\mathfrak c}\ge\omega_2$, for sure, but $\omega_2$ means here the "old one", the $\omega_2$ of $M$. Perhaps while adding reals by accident I added a bijection between the $\omega_2$ of $M$ and its $\omega_1$. Then perhaps in $M[f]$ we have ${\mathfrak c}=\omega_1$. (cont.)
Comment: (cont.) If, on the other hand, I am careful and make sure that "cardinals are the same", then in $M[f]$ I will have ${\mathfrak c}\ge\omega_2$, and $\omega_2$ is the "old one" but this is the same as the $\omega_2$ of $M[f]$, so really ${\mathfrak c}\ge\omega_2$, which is what we wanted.
Comment: @user18921 I do not see what is crazy about this. Anyway, the comment that starts "Literally" answers your question. The point is that what ordinals are cardinals is a matter of the existence of bijections between ordinals, and the ordinals do not change. The value of $\beth_1$ is a matter of the existence of a bijection between an ordinal and the set of reals (in the extension), and there may be new reals in the extension, so the set of reals in $M$ is not so relevant anymore.
Comment: @user18921 You are correct in saying that $\beth_\alpha^M$ and $\beth_\alpha^F$ could be different. The reason is that the former is computing the size of some power sets in $M$, and the latter is computing the size of the corresponding power sets in $F$. Since $F$ typically has more sets than $M$ did, what we expect is that these power sets are larger: If all ordinals and cardinals in $M$ and $F$ coincide, we necessarily have $\beth_\alpha^M\le\beth_\alpha^F$, and the inequality could be strict.
Comment: Thanks for your answer! Though I'm afraid I'm not in a position to appreciate it any overly precise way...
Comment: I guess this betrays that my accepting your answer was somewhat blind, but can I ask why the following is forbidden. The cardinality $c$ at least makes sense in ZFC so there is an ordinal $\alpha$ with $\aleph_\alpha = c$. Your first paragraph seems to suggest I should be able to find an extension of the universe of sets *with the same cardinals* where now $\aleph_\alpha > c$. You catch my drift? I'm not sure I understand what you mean by an extension with the same cardinals.
Comment: (I agree this may be somewhat confusing at first. To understand forcing requires some understanding of models of set theory, and of what it means for a statement to be true in a model, as opposed to it being true "in the universe of sets".)
Comment: (And I see that Steven explained the same issue while I was typing. Sorry for the overlap.)
Comment: Andres: Not at all!  I think the extra details on your answer are immensely useful, and I like it better than mine (which is a lot fuzzier on the specifics).
Comment: @Andres: Crash course in Cohen forcing over comments, eh? ;-)
Comment: Andres, you write a sentence to the effect that: "If you fix an ordinal α, then it is consistent that $\beth_1>\aleph_α$." Is this literally true? I mean, what if $\alpha = \beth_1$?
Comment: @user18921 Literally, what you have is this: Given any model $M$ of set theory, and any ordinal $\alpha$ of $M$, there is a forcing extension (essentially, another model of set theory) with the same ordinals and the same cardinals (meaning, if an ordinal $\beta$ was a cardinal of $M$, $\beta$ is still a cardinal of the extension, and any cardinal of the extension was one of $M$), and in this extension, $\beth_1>\aleph_\alpha$. If $\alpha=\beth_1$-of-$M$, all this means is that $\beth_1$-of-the-extension is strictly larger than $\beth_1$-of-$M$.
Comment: (@user18921 And it is not necessary to talk of models $M$ here, the discussion can be recast in a -- perhaps somewhat more cumbersome -- way that avoid this.)
Comment: @AndresCaicedo, *any* model, or should I be thinking of the standard ones?
Comment: @user18921 Any model. Again, we can recast the whole discussion in a way that models are not even mentioned. The standard presentation of forcing uses countable transitive models, and this approach is perhaps the most intuitive, but the restriction is completely unnecessary.
Comment: Hmmm okay. I accept that you're correct, but it seems crazy though. Why doesn't this imply that $\beth_1 > \aleph_{\beth_1}$?
Comment: Or rather, why doesn't it prove that $\beth_1 > \aleph_{\beth_1}$ is consistent with ZFC?
Comment: @AndresCaicedo, okay I think I get it. Would be fair to say the following? Let $M$ denote the model we started with and $F$ the forcing extension. Then for any ordinal $\alpha$ of our model; $\aleph_\alpha^M = \aleph_\alpha^F,$ but there is no guarantee that $\beth_\alpha^M = \beth_\alpha^F$. Indeed, $\beth_\alpha^F$ could be strictly smaller then $\beth_\alpha^M$ (because we introduced a bunch of bijections) or it could be strictly larger (because we introduced a bunch of elements into $\mathcal{P}(\beth_0),$ so the old bijections aren't bijections any more.)
Comment: Is that correct? I just want to make sure I'm not fooling myself here.
Comment: Actually on second thought, I'm not sure that $\beth_\alpha^F$ can be strictly smaller than $\beth_\alpha^M,$ assuming the ordinals and cardinals of our models agree.
Comment: @AndresCaicedo, thanks, that makes perfect sense.
Comment: @user18921 Now, there are forcing notions that for some $\alpha$, allow us find a $\beta<\beth_\alpha^M$ with a bijection between $\beth_\alpha^F$ and $\beta$, but when this happens, necessarily some cardinals of $M$ are no longer cardinals in $F$ (we added bijections witnessing this).


Passing multiple arguments to script linux

Question: I've got the following code, which is supposed to take filenames as arguments, and send them to my email address, which is derived from a username:
#Email Script from linux
#Define username e.g. pp_roman
u="$USER"

#Remove the pp_ and store to variable e.g. roman

u2=${u#"pp_"}

#Define Email portion

em="@workemail.com"

#Combine the username e.g. firstname.lastname@example.com

u3=$u2$em

#Arguments for script

for FILE1 in "$@"
do
    filename="-a $FILE1"
done

##This returns the full string with $filename variables for arguments, and email from $u3

mailx $filename -s "Subject" $u3 < /dev/null

However when passing multiple arguments, only the last mentioned filename is sent as an attachment. How do I pass multiple arguments into the $filename variable all appended by "-a"?
Comment: What shell are you actually using? `bash`, `ksh`, `zsh`, `dash`? Or does this need to conform to the POSIX specification for portability?
Comment: bash. Currently looking at adding functionality to refuse transfer of files over say 5 meg? don't know how resource intensive mailx is.
Answer: Since you are using bash, the right thing to use is an array.
attachments=()
for f in "$@"
do
    attachments+=(-a "$f")
done

mailx "${attachments[@]}" -s "Subject" "$u3" < /dev/null

Comment: Would this work for filenames with whitespaces? Previous comment suggested single quotes for '$f', or is this the type input for arrays?
Comment: Quoted array expansion using `[@]` is specifically designed to solve the problem of storing a sequence of values containing whitespace.


corrgram package dependencies

Question: I have installed R 3.3.2, compiled from source in Ubuntu 14.04. I tried to install corrgram package like
1) install.packages("corrgram")
2) devtools::install_github("kwstat/corrgram")
but a number of dependency errors a showed.
There are dependencies like seriation, dedextend, fpc, flexmix and have no idea what these packages are.
Answer: I had the same problem. The reason for its occurrence was a package installation problem for the nloptr package in the 'dependency-chain' of corrgram. I could solve it by manually installing

sudo apt-get install libnlopt-dev

as described here: Installing nloptr on Linux

corrgram package dependencies


Erro ao abrir arquivo excel exportado em PHP

Question: Uso o seguinte código:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="bootstrap/style.css">
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="bootstrap/css/datatables.css">

    <link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

LOJA:  <?php echo"00$v_loja ";?>

USUARIO:  <?php echo"$v_nome $v_sobrenome ";?>

 SAIR

             VOLTAR
             EXPORTAR
      <?php
      $query_frase = mysql_query("SELECT
     frase_id   AS ID,
     frase_desc AS DESCRICAO
       FROM frases_sistema ");
        while ($row = mysql_fetch_array($query_frase)) {
        $v_frase    = $row["DESCRICAO"];
           }

        ?>

<?php echo"$v_frase";?>

<?php echo"$v_descricao_categoria"; ?>

      <link rel="stylesheet" type="text/css" href="/Content/font-awesome/css/font-awesome.min.css" />

            ITEM
            DESCRICAO
            DIAS_DE_GIRO
            FATOR
            ESTOQUE
            NECESSIDADE
            PEDIDO
            BANCAO
            ROMANEIO
            TRANSITO
            GONDOLA
            REPOSICAO

      <?php
         echo"
";
         while ($row = mysql_fetch_array($sql_retorno)) {
         echo"
";
            echo" ".$row['ITEM'].                             "	";
            echo"".$row['DESCRICAO'].                        "	";
            echo"".$row['DIAS_DE_GIRO'].                  "	";
            echo"".$row['FATOR'].                         "	";
            echo"".$row['ESTOQUE'].                       "	";
            echo"".$row['NECESSIDADE']. "	";
            echo"".$row['PEDIDO'].      "	";
            echo"".$row['BANCAO'].      "	";
            echo"".$row['ROMANEIO'].    "	";
            echo"".$row['TRANSITO'].    "	";
            echo"".$row['GONDOLA'].     "	";
            echo"".$row['REPOSICAO'].   "	";
         echo"
";
            }
      echo"
";
     echo"
";

    ?>

    <link rel="stylesheet" type="text/css" href="http://www.shieldui.com/shared/components/latest/css/light/all.min.css" />

Exporta perfeitamente, mas ao abrir dá essas 2 mensagens:

Se eu der sim e depois fechar abre normalmente, mas gostaria de remover essas mensagens.
Alguém sabe o que pode ser?
Comment: Queria entender essas tags aí.
Comment: Isso ocorre por segurança. Você gostaria que o Excel executasse um código qualquer de um arquivo que você acabou de baixar da Internet?
Answer: Otácio, veja este link:
Autoexecutar macros no Excel
No teu caso, como o Excel está sendo executado e por isso dá essas mensagens, veja se é possível solucionar pela autoexecução de uma macro "antes" do teu processo de leitura ser carregado.
De outro modo, se o Excel vai ser executado de qualquer forma, você poderia tentar criar uma macro de leitura adequada para o teu caso. Sei que não é o ideal devido à sua pergunta.
Veja se a primeira dica resolve, boa sorte!
Comment: Só uma observação: **configurar o Excel para executar código automaticamente pode levar a graves brechas de segurança**. Isto não é recomendável em praticamente nenhuma ocasião, principalmente quando se fala num ambiente de trabalho, pois pode permitir a terceiros capturar e monitorar os dados do computador.


Easy to use DAW

Question: I am currently using open-source DAW program LMMS but it is very difficult to me. Is there any easier program for a beginner? Or which one do you most recommend except Logic Pro because i do not have any Mac.
Answer: FL Studio is quite simple to use. It's very powerful, too.
You can buy the basic version for only 99$.

Easy to use DAW


Word2vec raise KeyError(f"Key '{key}' not present")

Question: Currently using gensim 4.0 library to write the code. However, I don't know why it keeps failing in finding a similar word. At first, when I set up min_count = 5, the error is, that it wants me to build a vocab first, but after I reduce it to min_count = 1, it says, key error not present...Full code with datasets over here: https://github.com/JYjunyang/FYPDEMO Am I writing something wrong or missing some important steps? Everything works fine but just this word2vec implementation...Will appreciate for every guidance provided...
Take note: LemmaColumn is a dataframe after lemmatization
def FeaturesExtraction():
    word2vec =
Word2Vec(sentences=LemmaColumn,vector_size=100,window=5,min_count=1,workers=8,sg=1)
    b1 = time.time()
    train_time = time.time() - b1
    print(word2vec.wv.most_similar('virus', topn=10))

And I not sure why, after training with 10k data, unique words in vocabulary only have 7:
word #0/7 is t
word #1/7 is l
word #2/7 is x
word #3/7 is e
word #4/7 is _
word #5/7 is u
word #6/7 is f
Answer: Your LemmaColumn variable probably isn't in the format Word2Vec needs for the sentences argument. It needs a Python sequence: something than can be iterated over multiple times, like a list, or another re-iterable object. And in that sequence, every individual item must itself be a list-of-string-tokens (words).
Your tiny vocabulary is instead what I'd expect to see if instead:
LemmaColumn = [
    ['f', 'u', 'l', 'l', '-', 't', 'e', 'x', 't'],
]

…or even…
LemmaColumn = [
    ['full-text'],
]

…because Python will happily treat a plain string (like 'full-text') as if it were a list filled with 1-character strings. Thus your entire training vocabular is only the characters of that single string – likely a column-name, rather than the column-data you want to be using.
Double-check what's in LemmaColumn. Perform the necessary transformations on the column's data to make it the kind of sequence Word2Vec expects, & confirm it looks sensible before trying Word2Vec.
Also: running with logging on to at least the INFO level will show a lot more of the model's progress, and as you learn to understand the reported steps/progress, things like weirdly-low counts of texts/words, or steps that'd take time if they were working on the right amount (lots) of data completing instantly, will be evident sooner.
Finally, note that min_count=1 is essentially always a bad idea with an algorithm like word2vec. Good vectors only come from multiple varied examples of the same word's usage – hence the default min_count=5. Keeping rare words not only tends to get poor vectors for those rare words, but the fact that natural-language text tends to have lots of such rare words means so much of the model's time & space is devoted to the (nearly hopeless) task of improving those junk words' vectors that other nearby words' vectors suffer as well.
Comment: thanks for the help! I was able to solve it now! However, only 20 unique words are available for this model. May I ask is it my parameter problem causing these low unique words? Because the original dataset was 600k...
Parameter I used:
word2vec = Word2Vec(sentence,vector_size=300,window=5,workers=8,min_count=1,sg=1,negative=5,ns_exponent=5,max_vocab_size=None)
Comment: What are the 20 words? Have you examined the data you're passing in to make sure it's the right format? (That is: a re-iterable Python sequence where each item is a list-of-strings.) Also, `min_count=1` still a bad idea for real work (as opposed to quickie tests), and `ns_exponent=5` is a bizarre choice I've never seen before, so odd to see from someone still struggling to get basic stuff working. Where was that non-default value suggested as a good idea?


Select all nodes that reference the current node

Question: I'm new to Drupal and am wondering if anyone could provide direction on this.
Basically I have 2 content types - one called 'clinics' and one called 'clinic groups'. Each 'clinic' has a node-reference to a 'clinic group' node. What I'm trying to achieve is basically, if I'm on the 'clinic group' page - I'd like to pull back all the nodes 'clinics' under it, that reference it.
Is this possible in views?
Thanks everyone.
Answer: You could do this using views.Create a view where under
<code>Fields you select your group as Node, Under that choose Title.

For Filters select Node Type, Operator: Is one of and select Clinic content type.

Under Arguments select your group as Content. Under that choose Clinic_group (the node reference field).
</code>
You can add additional parameters to your view like Number of items to display, more fields like Node: Body and maybe a filter that Node: Published, select yes.
To see a preview, under live preview give the arguments as node number and click Preview.
Hope this helps!
Answer: Not sure if it works with Views by itself, but the Node Relationships module uses customized views for output.


How come the definition of a limit does not have $0\lt |f(x) - L| \lt \epsilon$ instead of $|f(x) -L|\lt \epsilon$?

Question: We know that the definition of a limit is: $\forall \epsilon > 0 \space \exists\delta>0, 0<|x-c|<\delta \to |f(x) - L| < \epsilon$
From my understanding, this means that the closer $x$ gets to $c$, then the closer $f(x)$ gets to $L$. However, since $x$ is never actually at $c$, then isn't it impossible for $f(x) = L$? If so, then why don't write $0<|x-c|<\delta \to 0<|f(x) - L| < \epsilon$ since it $f(x)$ can never equal $L$?
Answer: It is possible for $f(x)$ to be $L$, even if $x\neq c$.
Maybe $f$ takes the value $L$ at another point than $c$. This happens for instance for all constant functions.
Comment: Rephrased:  If you would like constant functions to have limits you better use the standard definition.
Answer: Is such an example what you are after: If $f(x) = 1$, then $f(x) = f(1)$ for all $x \neq 1$.
Answer: Let $f$ be the function such that
$$f(x)=\begin{cases}
x\sin(1/x)&,x\ne0\\\\
C&,x=0
\end{cases}
$$
where $C$ is an arbitrary number.
Then, we have $\lim_{x\to 0}f(x)=0$.
Note that $f(x)=0$ for an infinite number of values of $x$ on any deleted neighborhood of $x$ (i.e., just take $x=1/(n\pi)$ for any integer $n\ne 0$).  And this is true despite the fact that $f(0)=C$ for any $C$.


Table doesn't exist on CRE Loaded 6.2 install

Question: I want to install CRE Loaded 6.2 on my local machine running XAMPP server but it's showing the following error:

1146 - Table 'creloader.configuration' doesn't exist
  select configuration_key as cfgKey, configuration_value as cfgValue from configuration
  TEP_DB_ERROR

What does it mean? I also created database named creloader.
Answer: I don't know what is creloded6.2 but in all installation packages there is a sql file you have to run in your database, it seems you haven't done it.


How can I fix a call to undefined function libraries_load() in GeShi Filter?

Question: I just installed GeSHi Filter and had to install the Libraries API for it. When I try to go to configuration settings I get this error:
Fatal error: Call to undefined function libraries_load() in /home/username/public_html/drupal/sites/all/modules/geshifilter/geshifilter.module on line 23

For the moment, I uninstalled all the above modules and its back to normal. Does anyone have any idea on how to fix it?
Answer: It appears you tried to use the recommended branch of Libraries API (marked green): 7.x-1.0. Generally, this is a good thing to do, but it can cause problems when modules have dependencies that are still in development.
In this case, Libraries API 7.x-1.0 doesn't the define the libraries_load() function that GeSHi Filter needs. You need to use the latest 7.x-2.x development snapshot.
Answer: As reported in the project page, you should use the development snapshot 7.x-2.x-dev of the Libraries API module for the branch 7.x-1 of the GeSHi Filter module.

The 7.x branch requires the Libraries API (2.x-dev). A drush make file is also included that will download both the libraries API and the geshi dependency.


In guitar, do consecutive frets on the same string play notes from the same octave?

Question: If I move to consecutive frets on the same string, are notes produced from the same octave?
For example, is it possible to play the first 5 notes of C major scale on the A string? (C, D, E, F, G)? Why do we play D note on the open string instead of moving down the same string?
Comment: An octave is an interval, not a fixed set of notes. Any two adjacent frets will produce notes in *an* octave.
Answer: Yes, you can play C major scale the way you show, and there is nothing wrong with it. Actually there is some benefit, as notes on different strings sound slightly differently (e.g. compare sound of D on the open D string, and D on 5th fret of the A string), so playing on a single string gives you the most consistent sound.
But there are also downsides: you need to move your fretting hand a lot, and you are limited in how high or how low the melody can move. It complicates even more if you want to play several notes at the same time, like chords, or polyphonic lines. These are reasons to split melodies onto multiple strings.
I'll also answer the title question, even if it's perhaps not worded the best: The convention is to name C as the lowest note in each octave. So e.g. C on the 3rd fret of the A string is called C₃; then D on the 5th fret is D₃; up to B on the 14th fret is B₃, and then C on 15th fret is C₄, it starts next octave. Similarly B on the 2nd fret of A string is B₂, so it belongs to the octave below C₃. That's naming convention. If you play C₃ and you want to move half tone down, you play B₂, and there is nothing wrong in the fact that you move to an octave with a lower number.
Answer: I'm going to add some useful information about the guitar to the capable answers already provided. One of the characteristics of the guitar is that with the exception of the lowest 5 notes on the low E string and the highest 5 notes on the high E string every note on the guitar exists in at least 2 places on the instrument. Most middle register notes are available in 3 to 5 different places. As a matter of fact, if you have a 24 fret guitar the open high E note actually can be played in 6 different places! Of course some are much better sounding than others, for example the 24th fret of the low E isn't going to sound very good.
What this gives you is the option to play a scale or anything else in many different ways by using one string or switching from one string to another.  Some are more logical than others and this is something you learn with education and practice.
Let's take your example of C D E F G. Here are 4 examples of ways those notes can be played on the guitar (there are several other ways to play this).

There is no right or wrong way and there are other ways as well. Usually the context or what comes before and after will determine which is best to use.
ADDITIONAL INFO:
A guitar is tuned in 4ths, which is the equivalent of 5 frets. The exception is the G and B strings are tuned a major 3rd, or 4 frets apart. The 5th fret of the low E string is A, the same as the open A string. The A string 5th fret is D, same as the open D string, etc.
If you study the fingerboard diagram you used in your question you will notice something. Any note has its equal note either 5 frets higher on the adjacent lower string OR 5 frets lower on the adjacent higher string. (Except for the G and B which would be 4 frets). If this isn't clear I will give an example:
Take the note E on the A string, 7th fret. That note is duplicated on the E string 12th fret (one string lower and 5 frets higher) and also on the D string 2nd fret (one string higher, 5 frets lower).
You can look for other examples on your own. This will help you learn the fingerboard little by little. It may seem overly complicated but in the end it actually makes sense because the sequence of notes is always the same, it just repeats in different positions on different strings.
Comment: A couple of weeks ago Jonathan Kreisberg published this commentary on YouTube about [how many choices guitarists have.](https://www.youtube.com/watch?v=qWM-mI5__C0)
Comment: @exnihilo Wow, 16 ways, and that doesn't include positions with more unusual or awkward position jumps!
Comment: @ShamitVerma My pleasure. I am going to add more detailed information to my answer that will be useful to you…
Comment: " ..note on the guitar exists in at least 2 places on the instrument .. "

Thanks for the insight. As a beginner, this is very helpful to know.
Never thought of this as a possibility.
Comment: @ShamitVerma there are also at least 5 versions of each named chord, usually described by the shape of the basic open chord forms.  see "CAGED" https://www.youtube.com/watch?v=roVQGKPSasw
Answer: Short answer: yes.  You're right.  You can play almost 2 octaves of a scale on a single string (maybe more if you're bendy and have an electric guitar).
The reason not to play on the same string is that eventually, you'll run out of consecutive fingers to use and you'll have to move your hand laterally.  That will make it harder to play the notes smoothly, especially if playing fast.
Musically, the change in string does affect the sound tone as well, but that's not really the main reason for string choice.
Answer: Why do we play D note on open string instead of moving down the same string ?
Sometimes we do, sometimes we don't.
There are many ways to play a C scale, and the choices go to preferred style. For example, a folk style would like ringing open strings in the first position, but jazz and rock players would play it higher up the neck in part because it eases muting.
Playing that sequence up the neck would indicate, to me, a position change that would correspond to a change in style and tone, like many rock solos going higher in pitch to increase intensity.


R: converting a while loop to recursion

Question: I'm trying to convert a while loop to a recursion.
I know the while loop is more efficient, but I'm trying to understand how to convert a for/while loop to recursion, and recursion to a for/while/if loop.
my function as I'm using a while loop:
       harmon_sum <- function(x){
      n <- 1
      sum <- 0
      while (sum < x)
      {
        sum <- sum + (1/n)
        n <- (n +1)
      }
      return(n)
    }

This function takes some numeric value, suppose x=2, and returns the number of objects for the harmonic sum that you need to sum up  in order to create a greater number then x. (for x=2, you'd need to sum up the first 5 objects of the harmonic sum)
 [![harmonic sum][1]][1]

**example**: `harmon_sum <- function(x){
   n <- 1
   sum <- 0
   while (sum < x)
   {
     sum <- sum + (1/n)
     print(sum)
     n <- (n +1)
   print(n)
     }
   return(n)
 }

> harmon_sum(x =2)
[1] 1
[1] 2
[1] 1.5
[1] 3
[1] 1.833333
[1] 4
[1] 2.083333
[1] 5
[1] 5`

my version for the recursive function:
    harmon_sum2 <- function(x, n =1){
   if( x<= 0){
    return(n-1)
    }
  else {
    x <- (x- (1/(n)))
    harmon_sum2(x, n+1)
  }
}

which returns me the wrong answer.
I'd rather find a solution with just one variable (x), instead of using two variables (x, n), but I couldn't figure a way to do that.
Answer: It seems to me that if you change return(n-1) to return(n) you do get the right results.
harmon_sum2 <- function(x, n=1){
  if( x <= 0){
    return(n)
  }
  else {
    x <- (x- (1/(n)))
    harmon_sum2(x, n+1)
  }
}

harmon_sum(2)
[1] 5
harmon_sum2(2)
[1] 5
harmon_sum(4)
[1] 32
harmon_sum2(4)
[1] 32

Comment: I wouldn't know about that. To me it seems like you need to keep track of `n` as well. @Roland gives a solution for this. Otherwise, you could try to ask a new question for this. Maybe the sister website on theoretical computer science will be a better place to ask: https://cstheory.stackexchange.com/
Comment: is it possible to define the function where the input is consisted only in x?

I mean, `harmon_sum2 <- function(x)`

I know it must be possible because of the Church-Turing thesis
Answer: Your function needs to know n. If you don't want to pass it, you need to store it somewhere where all functions on the call stack can access it. For your specific case you can use sys.nframe instead:
harmon_sum2 <- function(x){
  if( x<= 0){
    return(sys.nframe())
  }
  else {
    x <- (x- (1/(sys.nframe())))
    harmon_sum2(x)
  }
}

harmon_sum(8)
#[1] 1675
harmon_sum2(8)
#[1] 1675

However, this doesn't work if you call your function from within another function:
print(harmon_sum2(8))
#[1] 4551

Another alternative is the approach I demonstrate in this answer.
Comment: but that returns a false answer
Comment: It returns the same answer as your original function?
Comment: It returns 5 on my system.

R: converting a while loop to recursion


Stored procedure, empty parameters

Question: I am working in c #, wpf with mvvm and a stored procedure in sql server 2008.
I have a problem when sending the values to the function where the stored procedure is executed, I get then from a form, where it can leave some fields empty. But these are objects of a class, then to access them should not be null. I leave the code.
        public IEnumerable<Model.AsuntoModel> GetBusqueda(Model.PrioridadModel prioridad, Model.StatusAsuntoModel statusasunto, Model.DestinatarioModel destinatario, Model.SignatarioModel signatario, DateTime rangofecha, DateTime referenciadocumento)
    {
        ObservableCollection<Model.AsuntoModel> Busqueda = new ObservableCollection<Model.AsuntoModel>();
        using (var entity = new GestorDocumentEntities())
        {

            try
             {
                 entity.GetAsuntos(prioridad.IdPrioridad, statusasunto.IdStatusAsunto, destinatario.IdDestinatario, signatario.IdSignatario, referenciadocumento).ToList().ForEach(p =>
                 {
                     Busqueda.Add(new Model.AsuntoModel()
                     {
                         IdAsunto = p.IdAsunto,
                         FechaCreacion = (DateTime)p.FechaCreacion,
                         FechaRecibido = (DateTime)p.FechaRecibido,
                         FechaDocumento = (DateTime)p.FechaDocumento,
                         Titulo = p.Titulo,
                         Descripcion = p.Descripcion,
                         Alcance = p.Alcance,
                         IdUbicacion = (long)p.IdUbicacion,
                         Ubicacion = new Model.UbicacionModel()
                         {
                             UbicacionName = p.CAT_UBICACION.UbicacionName
                         },
                         IdInstruccion = (long)p.IdInstruccion,
                         Instruccion = new Model.InstruccionModel()
                         {
                             InstruccionName = p.CAT_INSTRUCCION.InstruccionName
                         },
                         IdPrioridad = (long)p.IdPrioridad,
                         Prioridad = new Model.PrioridadModel()
                         {
                             PrioridadName = p.CAT_PRIORIDAD.PrioridadName
                         },
                         IdStatusAsunto = p.IdStatusAsunto,
                         StatusAsunto = new Model.StatusAsuntoModel()
                         {
                             StatusName = p.CAT_STATUS_ASUNTO.StatusName
                         },
                         FechaVencimiento = p.FechaVencimiento,
                         Folio = p.Folio
                     });
                 });

             }
            catch (Exception)
            {
                ;
            }
        }
        return Busqueda;
    }

Answer: Here's one of many solutions.
You simply make you SQL parameters nullable by giving them a default value.
E.g :
@ParamA = null
@ParamB = null
etc..

Then you manage this on the SQL side to see how many you've received.
This way, your query will have a valu (in this case null) for you parameters if you don't supply any. You can then test it like :
IF @ParamA IS NULL
BEGIN
-- You didn't give that param.
END
ELSE
-- You gave a param

Answer: Your SP can be coded to treat NULL parms as ANY.
select *
from table
where (table.col = @COL or @COL IS NULL)
and (table.col2 = @COL2 or @COL2 IS NULL)

Stored procedure, empty parameters


Problema ao renderizar porcentagem pequena no PieChartModel no Primefaces;

Question: Estou gerando um gráfico geralmente sem problemas, só ocorre com porcentagens menores, mostrando a 'fatia' corretamente, porém não é exibido o valor dessa porcentagem.
Tentei fazer a alteração do diâmetro do piechart, como vi que é possível no xhtml(no showcase é feito no Java, porém a propriedade de parâmetros não aparece para ser setada para mim).
Alguém já passou por isso, ou poderia me auxiliar?
Obs: utilizo Primefaces 3.5.
Segue abaixo o código que utilizo e a imagem do gráfico:
java:
this.graficoAteste = new PieChartModel();
...
graficoAteste.set("Sim", 33);
graficoAteste.set("Não", 2);
graficoAteste.set("Parcial", 1);
graficoAteste.set("Não Atestado", 0);

xhtml:

Answer: Opa, encontrei a solução para o meu caso.
A questão é que o PieChart do Primefaces utiliza uma biblioteca JQuery chamada JQPlot que, por padrão, não renderiza porcentagens abaixo de 3%.
Vendo isso, tive que sobrescrever alguns parametros via Javascript e utilizar o parametro extender no meu Piechart recebendo esse Javascript.
Ficando assim:
Piechart:

Javascript:

Onde dataLabelThreshold é a porcentagem mínima a ser renderizada e dataLabelPositionFactor é a distancia do centro do gráfico que o número deve ficar(0 a 1).


Should the distribution of the residuals of a regression model be symmetric about 0?

Question: Basically, should any decent regression model overestimate 50% of the time and underestimate 50% of the time (in the limit)?
In a scenario where a regression model outputs a price, which has to be non-negative, would the distribution of the residuals of an unbiased model still be expected to be ~symmetric around 0?
Or does the asymmetry in this price example mean that we expect the residual distribution to have a positive skew, since there's no limit to how much the model can overestimate but there is a limit to how much it can underestimate (due to the non-negativity)? Or does it depend on exactly what model is being used and the assumptions the model makes about its error terms?
If a positively skewed residual distribution is expected, is a simple regression adjustment of the predicted values a viable way to improve model accuracy?
Comment: 1. What do you mean by "decent" in the first sentence? What's the criterion?  2. Prices are non-negative but ordinary regression fits are not constrained in the way you suggest (which might be a reason not to use regression but that's a different issue to the one you ask about). A regression line can go negative within the range of the data even when all the data are positive.
Comment: With your price example are you imagining a constant error variance or are you imagining something where the scale is changing along with the mean? (I ask so that it's possible to come up with an illustrative example that matches your intent)
Answer: A skewed residuals distribution would imply that your model is biased and keeps over or under estimating. So i think the short answer to your question is yes.
In you example scenario your model would predict the conditional mean price. You want to avoid your model systematically over/under estimating the price which means that the residuals are ideally white noise / normal random variable.
Comment: Strictly speaking your model probably doesn't take the bound on price into account, and thus you would expect the residuals for an unbiased model to be symmetric around zero. If you model the problem with this constraint, that none of the regression predictions can ever be below zero, it's likely you'll get an asymmetric error distribution.
Comment: "*A skewed residuals distribution would imply that your model is biased and keeps over or under estimating*" --- can you explain how skewed residuals implies bias?
Comment: what i meant was that if the residuals distribution is highly skewed then that would imply that the model keeps over/under estimating and is a bad model for this data. my point was that the answer to @Taimur's question is yes, ideally you want the residuals to be normally distributed around 0.
Answer: For ordinary linear regression distribution of the residuals of a regression model should be symmetric about 0 since they should have a $N(0,\sigma^2(I-H))$
distribution.
Even the price is non-negative, the residuals still could be symmetric around $0$ since the structural component of the model i.e $Xb$ can be anything (include negative values). So using the ordinary least regression might not cause any bias.
However, if your residual is not symmetric about 0 then it suggests you might not use ordinary linear regression. You may consider generalized linear regressions.
The key is residuals not the value of price(i.e only be positive).


using string trim and toLowerCase methods in a single array map method not works as expected

Question: I have a string that I want to do a process to it:
1) split it by '.' and make an array
2) make each word and character to lower case
3) trim the array elements
I know that we can do this by coding each step separately but I want to do this in one line.
But it confused me why I can't do this using map(s => s.toLowerCase() && s.trim()) only the last method in the map works?
Any suggestions would be greatly appreciated.

let trapSt = '  I Was Sent = I Sent. To Earth = To Moon     '
trapSt = trapSt.split(".")
only_LowerCase_Works_Here = trapSt.map(s => s.trim() && s.toLowerCase()); // ??? why only s.toLowerCase() works here???!!!!
only_Trim_Works_Here = trapSt.map(s => s.toLowerCase() && s.trim()); // ??? why only s.trim() works here???!!!!

console.log(only_LowerCase_Works_Here);
console.log(only_Trim_Works_Here);
Comment: strings are immutable. You could chain the methods `s.toLowerCase().trim()` or you could simply use `toLowerCase` on the original string before doing the `split`.
Answer: Because toLowerCase and trim don't modify the string in place, they return the string after the modification.
The && isn't the same as:
s.toLowerCase().trim()

which is what you want.
Try this:
let trapSt = '  I Was Sent = I Sent. To Earth = To Moon     '
trapSt = trapSt.split(".")
only_LowerCase_Works_Here = trapSt.map(s => s.trim() && s.toLowerCase()); // ??? why only s.toLowerCase() works here???!!!!
only_Trim_Works_Here = trapSt.map(s => s.toLowerCase().trim()); // ??? why only s.trim() works here???!!!!

console.log(only_LowerCase_Works_Here);
console.log(only_Trim_Works_Here);

Comment: Thanks for the answer ... plus one... Actually I'm surprised how it worked... I remember `toLowerCase().trim()` resulted in errors before! that was why I used `&&`...
Comment: Not  a problem, and thanks! If the "string" in question is `null` or `undefined`, you will get errors. Other than that, any valid string should be able to go through `.toLowerCase().trim()`


Range of hashcodes in case of strings

Question: I have strings coming in my code and i take hashcode of them for some purpose but i was wondering that is there any range of these hashcodes because this may happen that the number of strings coming exceed the range of hashcodes.So what is the range of hashcodes?
Comment: The Range of hashCodes is Integer.MIN_VALUE to Integer.MAX_VALUE. and yes, most of the strings hascodes will be duplicated. Pigeon hole principle.
Answer: The range of hashCode is the range of int.  For any desired hashCode(), there is a String with that hashCode.
Answer: The hashCode method for String class in java is defined like this...
public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }

It will always have some value for your String.....So, i don;t think you will ever run out of hashCode's...

Range of hashcodes in case of strings


Problem with recaptchacontrol inside updatepanel

Question: I have a recaptchavalidator, which is inside an updatepanel:
        <asp:updatepanel runat=server id=updatepanel1>

    <cc1:recaptchacontrol runat=server publickey=.. privatekey=.. id=recaptchavalidator1/>
<asp:button runat=server id=button1/>
</updatepanel>

I am sure that some of you can guess what happens. For those of you who haven't experienced this before, the recaptchacontrol disappears! I have tried redirecting to the same page if the recaptchacontrol returns a false validation, but this has resulted in complex codebehind, and loss of veiwstate.
Is there a simple solution to this? I have looked over some articles on the web, but they seem to be complex and not well structured. I need to change the content of the updatepanel, so keep this in mind.
Thank you for your help.
Comment: This is what worked for me.  May not be the best solution but worth a shot: http://lakhlaniprashant.blogspot.com/2009/05/recaptchanet-control-in-updatepanel.html
Comment: Scratch that last comment.. it's not a full solution.
Answer: I got this to work nicely with just one updatepanel.
 <recaptcha:RecaptchaControl Theme="white"  ID="recaptcha" runat="server" PrivateKey="your_pub_key "
                                                    PublicKey="your_pub_key" />

    <asp:ScriptManager ID="ScriptManager1" runat="server">
                </asp:ScriptManager>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>

     <asp:Label Visible="false" ID="RecaptchaResult" runat="server" />
    <asp:Button ID="RecaptchaButton" runat="server" Text="Submit" onclick="btnSubmit_Click" />

    </ContentTemplate>
    </asp:UpdatePanel>

The key is to have your updatepanel set to conditional around your post button, so that you manually call the update to reload the recaptcha control from the server side.
Then, you call .update() on your panel after you've asked for the reload();
protected void btnSubmit_Click(object sender, EventArgs e)
        {
            recaptcha.Validate();

            if (recaptcha.IsValid)
            {
                RecaptchaResult.Text = "Success";

                RecaptchaResult.Text = "You got it!";
                RecaptchaResult.ForeColor = System.Drawing.Color.Green;
                RecaptchaResult.Visible = true;
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "recaptcha", "recaptcha.reload();", true);
                UpdatePanel1.Update();
            }
            else
            {
                RecaptchaResult.Text = this.recaptcha.ErrorMessage;
                RecaptchaResult.ForeColor = System.Drawing.Color.Red;
                RecaptchaResult.Visible = true;
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "recaptcha", "recaptcha.reload();", true);
                UpdatePanel1.Update();

            }

        }

Comment: Just a comment, I found that the `recaptcha.reload()` needed to be with an uppercase R i.e. `Recaptcha.reload()`.
Answer: Here is the answer that I have tried and is working:
ASP.Net, disappearing Recaptcha, UpdatePanels and Partial PostBacks: Fixed once and for all
Basically it involves creating a hidden div and using jquery to re-render the html.  Also the blog post gives a nice little breakdown of the typical solutions (e.g., using RegisterClientScriptBlock with a simple reload) and why they fail.

<recaptcha:RecaptchaControl ID="recaptcha" runat="server" Theme="clean" />

code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
  recaptcha.Validate();
  if (!Page.IsValid || !recaptcha.IsValid)
  {
    pbTarget.Visible = true;
    ScriptManager.RegisterClientScriptBlock(
      recaptcha,
      recaptcha.GetType(),
      "recaptcha",
      "Recaptcha._init_options(RecaptchaOptions);"
      + "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
      + "{"
      + "  if ( RecaptchaOptions.custom_theme_widget )"
      + "  {"
      + "    Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
      + "    Recaptcha.challenge_callback();"
      + "  }"
      + "} else {"
      + "  if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
      + "  {"
      + "    jQuery(\"#" + pbTarget.ClientID + "\").html('

');"
      + "    Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
      + "  }"
      + "  Recaptcha.reload();"
      + "  Recaptcha.challenge_callback();"
      + "}",
      true
    );

    return;
  }
  else
  {
    //normal page processing here...

Answer: Try this.
    <asp:UpdatePanel ID="ContactUpdatePanel" runat="server">
        <ContentTemplate>

                Name:
                <asp:TextBox ID="txtName" runat="server"
                        CssClass="textbox">
                </asp:TextBox>

                Address
                <asp:TextBox ID="txtAddress" runat="server"
                        CssClass="textbox"
                        Height="50px"
                        TextMode="MultiLine">
                </asp:TextBox>

                <recaptcha:RecaptchaControl ID="recaptcha" runat="server"
                                PublicKey="public key"
                                PrivateKey="private key"
                                Theme="white" />

                <asp:UpdatePanel ID="UpdatePanel2" runat="server"
                        ChildrenAsTriggers="false"
                        UpdateMode="Conditional">
                    <ContentTemplate>
                        <asp:Label ID="ErrorLabel" runat="server"
                                EnableViewState="false"
                                ForeColor="Red" />
                    </ContentTemplate>
                </asp:UpdatePanel>

                    <asp:Button ID="SubmitButton" runat="server"
                        onclick="SubmitButton_Click" Text="Submit" />

        </ContentTemplate>
    </asp:UpdatePanel>

Code-behind
protected void SubmitButton_Click(object sender, EventArgs e)
{
    try
    {
        this.recaptcha.Validate();
        if (recaptcha.IsValid)
        {
            //valid form. post it
        }
        else
        {
            ErrorLabel.Text = "Invalid Captcha. Please re-enter the words.";
            ScriptManager.RegisterClientScriptBlock(
                this.Page,
                this.Page.GetType(),
                "mykey",
                "Recaptcha.reload();",
                true);
            UpdatePanel2.Update();
        }
    }
    catch (Exception exception)
    {
        Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
    }
}

Comment: When I do this I get: `Uncaught TypeError: Cannot set property 'innerHTML' of null recaptcha.js:110
Recaptcha._set_challenge recaptcha.js:110
Recaptcha.finish_reload recaptcha.js:110
(anonymous function)`


Not able to install or update packages using Yum Local respository

Question: I have a Red hat 6.2 server which is in an isolated env which i need to update using Yum. I tried downloading the 51 GB reository from ftp://ftp.redhat.com/pub/redhat/linux/enterprise/6Server/en/os/ (which is the default URL as per default yum repo files) and conducted the below steps.

Deleted all repositories under /etc/yum.repos.d
Created a new repo file with below information
[localrepo]
name=LocalRepository
baseurl=file:///YUMREPO/SRPMS/Packages

gpgcheck=0
enabled=1

When i execute yum update, for the first time it is downloading the repository db properly however it is not updating anything new. When i try installing any other package e.g. vsftpd it fails to install as well mentioning the package not found, but the rpm files are present in the folder which i configured as repository.
# yum install vsftpd
Loaded plugins: product-id, security, subscription-manager

Updating certificate-based repositories.

Setting up Install Process

No package vsftpd available.

Error: Nothing to do

# ls -ltr /YUMREPO/SRPMS/Packages/vsftpd
-rw-r--r-- 1 root root 238016 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-11.el6.src.rpm
-rw-r--r-- 1 root root 239565 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-11.el6_4.1.src.rpm
-rw-r--r-- 1 root root 239801 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-12.el6_5.1.src.rpm
-rw-r--r-- 1 root root 240907 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-13.el6_6.1.src.rpm
-rw-r--r-- 1 root root 229354 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-6.el6.src.rpm

-rw-r--r-- 1 root root 242118 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-14.el6.src.rpm

-rw-r--r-- 1 root root 243417 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-14.el6_7.1.src.rpm

-rw-r--r-- 1 root root 230778 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-6.el6_0.1.src.rpm

-rw-r--r-- 1 root root 231280 Apr 14 08:18 /YUMREPO/SRPMS/Packages/vsftpd-2.2.2-6.el6_2.1.src.rpm

I have already tried using createrepo and createrepo -d (for sqllite db) but nothing works. Yum is not able to install any of the RPMs available in the folder.
When I do a repolist, the repository details are shown but Repo-pkgs and Repo-size are zero while the count shown under Repo-exculded is same as the number of rpm files in the repository directory.
# yum -v repolist
Not loading "rhnplugin" plugin, as it is disabled

Loading "product-id" plugin

Loading "security" plugin

Loading "subscription-manager" plugin

Updating certificate-based repositories.

Config time: 0.036

Yum Version: 3.2.29

Setting up Package Sacks

pkgsack time: 0.006

Repo-id      : localrepo

Repo-name    : LocalRepository

Repo-revision: 1460764382

Repo-updated : Sat Apr 16 08:13:29 2016

**Repo-pkgs    : 0

Repo-size    : 0
**
Repo-baseurl : file:///YUMREPO/SRPMS/Packages

Repo-expire  : 21,600 second(s) (last: Sat Apr 16 08:13:41 2016)

**Repo-excluded: 6,575**

I want to just configure the YUM repository for updating the packages and install new components. Due to security concerns CD and access to internet or any other network is blocked. In such isolated network, we can only use  authorized USB disks to copy the RPM packages. /YUMREPO is the mount location of the USB disk that is being used.
Comment: what did red hat say?
Answer: The ftp location that you refer to only contains sources to be re-compiled. Red Hat does not publish compiled updates, because you need to pay for them. That's their business model.
You can use CentOS systems. Or better pay Red Hat support fee for all the isolated systems (they actively develop Open Source projects, so giving them money is a Good Thing), install a separate system able to connect to Internet, subscribe the system to Red Hat and use the system to download the rpm files to the USB storage (not the src.rpm files!). The instructions how to subscribe will be available from Red Hat.


how to divide SUM(CASE...)es?

Question: I need to gain percentage by dividing two SUM variables. But when I try the code below, it gives me 0 as result. How can I divide these two SUMs?
Thanks!
(SUM(Case When FinalApprovalDt is not null and ContractPayoutAmt > 0 Then 1 else 0 End) / SUM(Case when FinalApprovalDt is not null then 1 else 0 end)* 100) As WriteRate
Answer: SQL Server does integer arithmetic, so 1/2 is 0 not 0.5.
You can write this by using a non-integer in the case expressions:
(SUM(Case when FinalApprovalDt is not null and ContractPayoutAmt > 0 Then 100.0 else 0 End) /
 SUM(Case when FinalApprovalDt is not null then 1 end)
) As WriteRate

Notice that I removed the else from the denominator.  This helps prevent divide-by-zero errors.
You can also write this without an explicit division as:
AVG(Case when FinalApprovalDt is not null and ContractPayoutAmt > 0 Then 100.0
         when FinalApprovalDt is not null then 0
    End) as WriteRate

This does an average over all rows where the FinalApprovalDt is not null, using the logic for the other column.
Comment: Throwing myself under the bus +1, but your second `AVG` option is probably the best way to go here.  Unless of course there is no chance of the denominator every being zero.
Answer: Force one of the CASE expressions to have decimal precision:
1.0 * SUM(CASE WHEN FinalApprovalDt IS NOT NULL AND ContractPayoutAmt > 0
               THEN 1 ELSE 0 END) /
      SUM(CASE WHEN FinalApprovalDt IS NOT NULL
               THEN 1 ELSE 0 END)* 100 AS WriteRate

I suspect that SQL Server treated both CASE expressions as integers.  When dividing integers, you would likely get truncation occurring.  So for a quotient less than 1, you would just see zero.
Note: I don't know why you are dividing by 100.  For a percentage, I would have expected you to multiply the numerator by 100.
Comment: @VBS Check Gordon's answer using `AVG()` for a possibly safer option, unless you are certain that the denominator could never be zero.
Answer: Please try like this ( Multiple the SUM of the numerator with 1.0 to make it decimal otherwise you will get integer division. )
SUM(Case When FinalApprovalDt is not null and ContractPayoutAmt > 0 Then 1 else 0 End) * 1.0
     / SUM(Case when FinalApprovalDt is not null then 1 else 0 end) * 100.0 ) As WriteRate

how to divide SUM(CASE...)es?


entityQuery condition for users without a role

Question: In Drupal 8 - Is there a way to do a 'NOT IN' in a user based entityQuery?
$uids = \Drupal::entityQuery('user')
      ->condition('uid', 72)
      ->condition('status', 1)
      ->sort('created', 'ASC')
      ->execute();

This query ^ yeilds results
$uids = \Drupal::entityQuery('user')
  ->condition('uid', 72)
  ->condition('roles', ['testing_user'], 'NOT IN')
  ->condition('status', 1)
  ->sort('created', 'ASC')
  ->execute();

This query ^ does not. User 72 doesn't have the role 'testing_user'
Comment: i didn't get it, you want to retrieve the users ids with roles not in `testing_user` and in the same time you add condition `condition('uid', 72)`?
Comment: So I'm just using that as a test condition. I will eventually be removing the uid 72. Sorry should have been more specific about this.
Comment: All I'm looking to do here is remove all results for testings_users. This code is being used in a bulk creation module to create content for all users. I'm trying to not create said content for users tagged with a testing_user role.
Comment: Why was this downvoted?
Answer: Your original code is correct. The problem is condition of 'not in'. It doesn't give result of users who has no roles. If you give roles to each user you are good to go.
More reading
You can get deeper understanding from class file
   https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Condition.php/class/Condition/8.2.x
Also there is a Drupal 7 API documentation about conditional-clauses
https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses
Answer:
Is there a way to do a 'NOT IN' in a user based entityQuery?

Yes, QueryInterface::condition $operator parameter documentation explicitly mentions NOT IN among other operators.
Operators are supported in several different ways based on the storage for an entity. For instance, "NOT IN" is supported via array_search in configuration entities and via the same manner as SelectInterface::condition for SQL-based entities.
Regardless of the manner the key is knowing the "field" to search on. You're working with an entity_reference field, which is more complex than a condition on a single column.
Perform a query with an entity field condition with multiple values shows this a little, but I hesitated to mark this one as a duplicate because it's not in the accepted answer.
Anyway the documentation for Entity QueryInterface mentions that the $field parameter

Name of the field being queried. It must contain a field name, optionally
  followed by a column name. The column can be the reference property,
  usually "entity", for reference fields and that can be followed
  similarly by a field name and so on. Additionally, the target entity type
  can be specified by appending the ":target_entity_type_id" to "entity".

So I think roles.target_id should work. If user_role entity was a content entity then the second part of the above statement would apply. Otherwise an exception will be thrown.
However @0-nur is correct: the roles field data stores information users who have roles so any query for a user that has the default roles will not be included in the query. You would need to add an additional condition. This is similar behavior to Drupal 7. In this case, since we're testing nullable we can use "roles" as the field.
$query = \Drupal::entityQuery('user');
$or = $query->orConditionGroup();
$or
  ->condition('roles.target_id', ['testing_user'], 'NOT IN')
  ->condition('roles', NULL, 'IS NULL');
$query->condition($or);


Is the kernel finite-dimensional if only finitely many basis-vectors of a Hilbert basis are mapped to zero?

Question: Let $H$ be a Hilbert space, $A$ a self-adjoint operator on a subspace of $H$ and $(v_n)_{n\in\mathbb N}$ a Hilbert basis (all $v_n$ are assumed to be in the domain of $A$). If $Av_n=0$ for at most finitely many $n$, can we already deduce that the kernel of $A$ is finite-dimensional?
Answer: No.  For instance, let $E\subset H$ be the subspace spanned by the vectors $v_{2n}+v_{2n+1}$ and let $A$ be the orthogonal projection onto $E$.  Then $Av_n\neq 0$ for all $n$ but $\ker(A)=E^\perp$ is infinite-dimensional (it contains $v_{2n}-v_{2n+1}$ for all $n$).
Answer: Let $A$ be  the orthogonal projection onto $$w=\sum_{n=1}^\infty 2^{-n/2}v_n$$ given by $Ax=\langle x,w\rangle w.$ Then $Av_n=2^{-n/2}w\neq 0$ and $\ker A=w^\perp$ is a subspace of codimension $1,$ so it is maximal possible kernel for a nonzero operator.


Percorrendo Datas utilizando Calendar

Question: Estou fazendo um relatório em java, que passo um período especificado pelo usuário. Na minha DAO eu estou fazendo o tratamento.
Aqui Pego a data passada.
String data1 = DateUtil.toString(dto.getDataInicio(), "MM/yyyy");
        String data2 =  DateUtil.toString(dto.getDataFim(), "MM/yyyy");

        Calendar c1 = DateUtil.parseCal (data1);
        Calendar c2 = DateUtil.parseCal (data2);

Aqui faço um tratamento para verificar os meses passados.
for (Calendar c = (Calendar) c1.clone(); c.compareTo (c2) <= 0; c.add (Calendar.DATE, +1)) {
           if (c.get (Calendar.MONTH) == Calendar.JANUARY  && c.get (Calendar.DAY_OF_MONTH) == 01){
                     mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-01-01', '"+c2.get(Calendar.YEAR)+"-01-01', to_char('"+c1.get(Calendar.YEAR)+"-01-01'::date, 'yyyy-mm'), cl.id_convenio) as janeiro, ";
                       nomesMeses.add("Janeiro");
               }
             if (c.get (Calendar.MONTH) == Calendar.FEBRUARY && c.get (Calendar.DAY_OF_MONTH) == 01){
                            mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-02-01', '"+c2.get(Calendar.YEAR)+"-02-01', to_char('"+c1.get(Calendar.YEAR)+"-02-01'::date, 'yyyy-mm'), cl.id_convenio) as fevereiro, ";
                            nomesMeses.add("Fevereiro");
               }
             if (c.get (Calendar.MONTH) == Calendar.MARCH && c.get (Calendar.DAY_OF_MONTH) == 01){
                            mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-03-01', '"+c2.get(Calendar.YEAR)+"-03-01', to_char('"+c1.get(Calendar.YEAR)+"-03-01'::date, 'yyyy-mm'), cl.id_convenio) as marco, ";
                            nomesMeses.add("Março");
               }
             if (c.get (Calendar.MONTH) == Calendar.APRIL && c.get (Calendar.DAY_OF_MONTH) == 01){
                            mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-04-01', '"+c2.get(Calendar.YEAR)+"-04-01', to_char('"+c1.get(Calendar.YEAR)+"-04-01'::date, 'yyyy-mm'), cl.id_convenio) as abril, ";
                            nomesMeses.add("Abril");
               }
             if (c.get (Calendar.MONTH) == Calendar.MAY && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-05-01', '"+c2.get(Calendar.YEAR)+"-05-01', to_char('"+c1.get(Calendar.YEAR)+"-05-01'::date, 'yyyy-mm'), cl.id_convenio) as maio, ";
                            nomesMeses.add("Maio");
               }
             if (c.get (Calendar.MONTH) == Calendar.JUNE && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-06-01', '"+c2.get(Calendar.YEAR)+"-06-01', to_char('"+c1.get(Calendar.YEAR)+"-06-01'::date, 'yyyy-mm'), cl.id_convenio) as junho,  ";
                            nomesMeses.add("Junho");
               }
             if (c.get (Calendar.MONTH) == Calendar.JULY && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-07-01', '"+c2.get(Calendar.YEAR)+"-07-01', to_char('"+c1.get(Calendar.YEAR)+"-07-01'::date, 'yyyy-mm'), cl.id_convenio) as julho, ";
                            nomesMeses.add("Julho");
               }
             if (c.get (Calendar.MONTH) == Calendar.AUGUST && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-08-01', '"+c2.get(Calendar.YEAR)+"-08-01', to_char('"+c1.get(Calendar.YEAR)+"-08-01'::date, 'yyyy-mm'), cl.id_convenio) as agosto, ";
                            nomesMeses.add("Agosto");
               }
             if (c.get (Calendar.MONTH) == Calendar.SEPTEMBER && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-09-01', '"+c2.get(Calendar.YEAR)+"-09-01', to_char('"+c1.get(Calendar.YEAR)+"-09-01'::date, 'yyyy-mm'), cl.id_convenio) as setembro, ";
                            nomesMeses.add("Setembro");
               }
             if (c.get (Calendar.MONTH) == Calendar.OCTOBER && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-10-01', '"+c2.get(Calendar.YEAR)+"-10-01', to_char('"+c1.get(Calendar.YEAR)+"-10-01'::date, 'yyyy-mm'), cl.id_convenio) as outubro, ";
                            nomesMeses.add("Outubro");
               }
             if (c.get (Calendar.MONTH) == Calendar.NOVEMBER && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-11-01', '"+c2.get(Calendar.YEAR)+"-11-01', to_char('"+c1.get(Calendar.YEAR)+"-11-01'::date, 'yyyy-mm'), cl.id_convenio) as novembro, ";
                            nomesMeses.add("Novembro");
               }
             if (c.get (Calendar.MONTH) == Calendar.DECEMBER && c.get (Calendar.DAY_OF_MONTH) == 01){
                           mesesql += "total_faturado_mensal(cs.id_corp, '"+c1.get(Calendar.YEAR)+"-12-01', '"+c2.get(Calendar.YEAR)+"-12-01', to_char('"+c1.get(Calendar.YEAR)+"-12-01'::date, 'yyyy-mm'), cl.id_convenio) as dezembro, ";
                            nomesMeses.add("Dezembro");
               }

            }

Está funcionando, porém ao informar um período por exemplo de 01/2016 há 12/2016 ele não está entrando dentro do if (c.get (Calendar.MONTH) == Calendar.DECEMBER trazendo então só de janeiro a Novembro.  Mas se eu coloco só 11/2016 e 12/2016 aparece o dezembro.
E para aparecer os 12 meses de 2016, eu tenho que colocar um mês amais por exemplo:
01/2016 á 01/2017 ai sim ele me traz o mês de dezembro.... e assim consequentemente, com datas maiores. Eu não intendo muito como funciona o Calendar, estou fazendo algo errado?
Comment: Recomendado: http://pt.stackoverflow.com/q/177129/132
Comment: Se você realmente quer usar `Calendar` (por que? :() um *workaround* conhecido é tornar o *range* aberto e utilizar o primeiro dia do mês seguinte, se precisar de outras opções de uma olhada [nessa pergunta](http://stackoverflow.com/q/3672052/664577). Dito isso, eu daria uma lida no link que o @VictorStafusa compartilhou e no [Tutorial Oficial da Oracle sobre Date Time API](https://docs.oracle.com/javase/tutorial/datetime/)
Comment: Month retorna o número do mês -1, ou seja, 11 será dezembro.
Comment: sim @diegofm, por isso comparo com Calendar.DECEMBER que  é um int 11. Mas funciona normalmente com os meses de janeiro a outubro. Sò nesses últimos está assim.  Eu achei casos parecidos com esse problema mas não resolveram.
Comment: Arthur, acho que o problema aqui é mais básico do que isso, a condição  `c.compareTo (c2) <= 0` é estrita e o Calendário leva em consideração campos além do mês e ano, estando eles presentes na data inicial ou não. Se você quer que a pesquisa seja inclusiva é necessário usar o último millisegundo do último segundo do último minuto da última hora do último dia do mês em questão (da mesma forma é importantente zerar todos esses valores para o primeiro dia).
Comment: Que classe é essa que você está usando: `DateUtil`?
Answer: Um detalhe que achei suspeito é que no for, você está incrementando dias, e não meses. Em qualquer dia que não for um dia 01, a iteração do for não vai fazer nada, apenas ficar pulando dia após dia. Além disso, a quantidade de código repetido é imensa. Por isso, vamos refazer o seu código:
String data1 = DateUtil.toString(dto.getDataInicio(), "MM/yyyy");
String data2 = DateUtil.toString(dto.getDataFim(), "MM/yyyy");

Calendar c1 = DateUtil.parseCal(data1);
Calendar c2 = DateUtil.parseCal(data2);

String[] meses = {
    "zero",
    "Janeiro", "Fevereiro", "Março", "Abril",
    "Maio", "Junho", "Julho", "Agosto",
    "Setembro", "Outubro", "Novembro", "Dezembro"
};

String template = "total_faturado_mensal(cs.id_corp, '$A-$I-01', '$B-$I-01', to_char('$A-$I-01'::date, 'yyyy-mm'), cl.id_convenio) as $M, ";

StringBuilder sb = new StringBuilder(8192);
sb.append(mesesql);

Calendar c = (Calendar) c1.clone();
while (c.compareTo(c2) <= 0) {
    int mes = c.get(Calendar.MONTH) + 1;
    sb.append(template
            .replace("$A", String.valueOf(c1.get(Calendar.YEAR)))
            .replace("$B", String.valueOf(c2.get(Calendar.YEAR)))
            .replace("$M", meses[mes])
            .replace("$I", mes < 10 ? "0" + mes : "" + mes));
    nomesMeses.add(meses[mes]);
    c.add(Calendar.MONTH, 1);
    c.set(Calendar.DATE, 1);
}

mesesql = sb.toString();

Neste código acima, estou supondo que a classe DateUtil funciona e não tem nenhum bug ou surpresa. Se não for este o caso, pode ser que dê errado, mas aí você vai ter que postar ao menos os métodos toString e parseCal dela para darmos uma olhada.
Outra alternativa é usando as classes do pacote java.time, muito melhores do que usar a horrorosa java.util.Calendar. Eis como fica o código nesse caso:
Date a = dto.getDataInicio();
Date b = dto.getDataFim();

LocalDate c1 = a.toInstant().atOffset(ZoneOffset.UTC).toLocalDate().withDayOfMonth(1);
LocalDate c2 = b.toInstant().atOffset(ZoneOffset.UTC).toLocalDate().withDayOfMonth(1);

String[] meses = {
    "zero",
    "Janeiro", "Fevereiro", "Março", "Abril",
    "Maio", "Junho", "Julho", "Agosto",
    "Setembro", "Outubro", "Novembro", "Dezembro"
};

String template = "total_faturado_mensal(cs.id_corp, '$A-$I-01', '$B-$I-01', to_char('$A-$I-01'::date, 'yyyy-mm'), cl.id_convenio) as $M, ";

StringBuilder sb = new StringBuilder(8192);
sb.append(mesesql);

for (LocalDate c = c1; c.compareTo(c2) <= 0; c = c.plusMonths(1)) {
    int mes = c.getMonth().getValue();
    sb.append(template
            .replace("$A", String.valueOf(c1.getYear()))
            .replace("$B", String.valueOf(c2.getYear()))
            .replace("$M", meses[mes])
            .replace("$I", mes < 10 ? "0" + mes : "" + mes));
    nomesMeses.add(meses[mes]);
}

mesesql = sb.toString();

E neste código, é claro que se você puder mudar o dto.getDataInicio() e o dto.getDataFim() para retornar LocalDate ao invés de Date, fica mais fácil.
Comment: Os dois métodos deu certo. Obrigado. Realmente ficou mais limpo e bunito o codigo.

Percorrendo Datas utilizando Calendar