Questionnaire design

Question: Answers to a questionnaire - Frequency of activity X

1 - 5
6 - 10
10 - 20
20 or more

I have two questions regarding these answers:

Uneven bins, the answer 10 to 20 has twice the number of numerical answers, if you were to analyse this data after collection, what implications would this have?
Similarly the final answer, an open ended upper bound. I am advised to estimate the average for this category, I disagree as we wont know the upper limit of the answer.

Your thoughts on this would be greatly appreciated.
Comment: I don't think you have a way to estimate the average for the upper category unless you make an assumption about the distributional form.
Comment: Either would work -- if you do it only for the last category you'd have to assume the parameter values; if you do it for all categories you can use the values you have to estimate the parameters (you could use techniques that deal with censoring).
Comment: Thank you. An assumption about the distribution of answers for all?
Comment: As opposed to the distribution of answers which fall into that category?
Comment: This is what I thought. Do you have any insight on uneven intervals when the distribution is unknown?
Comment: I am trying to find additional information, do you know what this type of answer is commonly described as?
Comment: With frequency of activity there is sometimes a theoretical maximum or near maximum. This would depend on what it is you are asking about
Comment: Frequency of use of particular items in and around the home.
Answer: a) Uneven bins, the answer 10 to 20 has twice the number of numerical answers, if you were to analyse this data after collection, what implications would this have?
The first implication is I'd probably laugh out loud at the person who designed the questionnaire (do it internally if the person is close by), and secretly put him/her under my crazy list.
The second implication is to remember last time I tried to use red wine vinegar when the recipes was calling for red wine and that didn't turn out so well. So, I'll just man up, take this as an ordinal variable, and try not to be overly creative with substituting anything.
b) Similarly the final answer, an open ended upper bound. I am advised to estimate the average for this category, I disagree as we wont know the upper limit of the answer.
That depends on who advised me to do that. If it's an unknown reviewer, I'd just scan the pages about central tendency from any intro statistics book, circle "median" or "mode" and send that back the median or mode.
If it's someone in power like my boss (who is already on my crazy list,) I'll probably suggest some distributions (I'd start with Poisson, but it's up to anyone's guess,) simulate with an array of parameters (e.g. lambda) and categorize the results according to the weird categorization until the percentages agree. The catch is that the result is going to be wrong cause it's hard to find a behavior that is only influenced by one distribution.
Also, where is the answer for 0 activity?

Why would you laugh out loud? Yes internally!
Please kindly forgive my humor. In many case this kind bastard children between a continuous and an ordinal variables just make me feel sad and funny the same time. We really didn't save too much respondents' burden in answering the question, but we kind of put in a difficult situation later. Should the 10-20 were broken down by an increment of 5, and if 20+ has a very small count, some kind of "trimmed mean" can still be a convincing alternative.
And speaking about trimmed mean, if not many of them are in 20+ (say, <2%), you may actually consider trimmed mean. You'll still need to approximate the mean in each bracket, but at least it's more reasonable.
Would you suggest using an upper bound for the final answer?
Depends on what the activity is. If not too much burden I'll ask for the actual number. If it's too much burden, I'd revise the category so that perhaps no more than a few percent of people will choose the top category.
Comment: Great insight, many thanks. Why would you laugh out loud? Yes internally!
Comment: Would you suggest using an upper bound for the final answer?
Comment: Oh - answer for 0 activity, there is one in the original question, I appear to have omitted it whilst re-writing it

Questionnaire design


How to Practice the Hanon Exercises

Question: I've played piano for many years but I'd like to do some work on my technique and am going to attack the Hanon exercises.  I have a very simple question on the instructions though. You are instructed to play each exercise initially slow (eg at 60bpm) moving up to fast (eg at 108bpm).
Is the book intending for you to master the entire first part (20 exercises) at 60bpm before increasing the tempo, or are you supposed to master each exercise up to fast before going on to the next?
I've read the instructions several times but can't decide which it means!   I think I could make a good argument for doing either, but I'd rather stick to what is best practice.
Comment: Great question Phil, and welcome to the site! If you found an answer helpful, please remember to upvote it to say thank you, and mark the most useful question as the solution for future visitors. You can learn more about how this site works [here on the tour page.](http://music.stackexchange.com/tour)
Answer: The book doesn't specify what path to take for a good reason and that is the final goal is to master them a faster speed and exact path you take isn't as important as where you end up. A simple example is you may find that exercise 2 is easier for you then exercise 1 so you may be able to master exercise 2 at a bpm of 108 before you are able to master exercise 1 at 60 bpm. This most likely isn't the case, but you get the idea.
The Hanon exercises are very intensive and take a while to master. I suggest you only focus on one or two exercises at a time at a low bpm initially maybe even lower than 60 if you are having a lot of trouble. It will take a while to master each. This site plays the execerizes for you and you can get an idea of how long it will take to play just the first excersize at 60 bpm not even considering you tying to lean it. When you master them and can play them faster you can string together a few exercises and use it as an excellent warm up for playing.
Answer: Usually with a book of etudes, the thing to do is to work on one for about two weeks, give or take, allowing the tempo to increase by itself, guided by comfort, and then move on to the next etude.  After a couple of months of this, you can start cycling back to the first, and continuing to review.  This means that if you spend 8 minutes working on the etude you are currently studying, you should spend 2 - 4 minutes on etude repertoire review.  The second time you work something up, it will go much quicker than it did the first time around, even if it's been six months since the time you last played it.  And chances are that the second time around you'll achieve a faster tempo than you got the first time around.
I will tell you frankly that we can't stand Hanon at our house, and use Donald Waxman's Exertudes instead.  Perhaps you would like to give this a try in addition to your Hanon.  The Waxman books are quite affordable.  It may not be in stock in your local shop, but it's easy to order.
The Waxman etudes are interesting harmonically, with some nice surprises, and contain many different aspects of piano technique.  There are several different levels in the series.  Even the first volume has lots of interesting and fun things going on.
Comment: That is certainly a drawback of Waxman, from your point of view.  - - -  There are rock, jazz and blues versions of Hanon that you might want to look into.  They don't have as much emphasis on note reading as the Waxman has -- they work more with patterns.
Comment: Thanks man =)   Yeah the hanon are painfully dull, but I have already found that they "work", in terms of building dexterity and freedom, and so am going to persevere through them.   They're also very easy to learn/sightread... which means all the time is spent on developing the technique without need to learn new musics.  Meaning I can spend more time on my own music after the drills.   Thank you!
Answer: When doing any technical exercise, like Hanon, practice moving as quickly as you can with good technique. Think of scales - when you were learning them, you did them until you "learned" them, and then added more. As you progressed, you learn to get the tempo higher more quickly than on the previous one, and the ones you already learned continued to get faster.
Hanon is really the same idea, just a lot fancier.
So work I one up to 60 or so, then start II, but revisit I periodically and keep increasing the tempo. Trying to get a particular exercise from a set very fast before going to the next will not be as helpful as doing many exercises at a medium speed, but at the same time, there's no reason to hold yourself back. Keep playing as fast as you can with excellent technique.
The exception is if you're playing Hanon Part 1 as a complete piece, then you'd want to keep the tempo intact throughout. Generally though that will be at a high speed.
I'm not sure if this is a "normal" way to work through Hanon, but my piano teacher had us to each exercise 3 ways once we reached a late intermediate level:

mf ("normal")
Slow, loud, legato, and with exaggerated finger motion (focusing on finger independence)
Fast, very soft, and staccato
Answer: Another point is to play many of the Part I exercises in several/many different keys (rather than just all "in C"). This benefits both finger adeptness, and muscle memory of more keys.
Also, playing sometimes staccato, sometimes legato, and with variations in emphasis.
Forcibly converting some of the exercises to 3/4 rather than 4/4 is an interesting mental and muscle exercise.
If you are bored, you can try doing things not in parallel octaves, but parallel tenths, and or in two different keys simultaneously. Mind-expanding. :)
(I should add that, many years ago, I did finally get myself to take such etudes seriously, and although I could already "play the piano" to a certain exteny, the improvements in my finger capacity were really gratifying, maybe already after a few months. Like doing some systematic weight training for a sport. It can be its own fun, too.)

How to Practice the Hanon Exercises


Show that G is profinite

Question:
Let G be a compact group, H be an open subgroup of G. Show that if H is profinite, then G is also profinite.

Lemma to use as a hint is this:

Let G be a compact group and $ {N_i | i \in I}$ be directed family of closed normal subgroups of G of finite index such that $\cap N_i=1.$(i.e. intersection of them is 1). Then G is profinite.

I know that if H is open subgroup, then H is closed of finite index and since it is profinite, H is inverse limit of inverse limit systen of finite groups. Somehow I have to construct these $N_i$'s from the closed subgroups that construct H. I also know that intersection of all open normal sungroups is 1. But I cant see the way to combine al of these. Any hint is welcomed.
Answer: An application of the Van-Dantzig theorem is that a topological group (Hausdorff) is profinite if and only if it is compact and totally disconnected.
Now, the proof follows easily: H is clopen and totally disconnected, hence G is totally disconnected as well. But G is compact and so it is profinite.

Show that G is profinite


Nginx: How to limit request rate based on user agent

Question: Trying to get the following behavior working in nginx
A default rate limit of 1r/s for each ip when using a browser.
A rate limit of 10r/s for bing and google spiders.
Reject bad bots.
Unfortunately google doesn't publish ip addresses for googlebot so I'm limited to useragent.
So far this gets close:
http {
  # Rate limits
  map $http_user_agent $uatype {
    default 'user';
    ~*(google|bing|msnbot) 'okbot';
    ~*(slurp|nastybot) 'badbot';
  }

  limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
  limit_req_zone $binary_remote_addr zone=two:10m rate=10r/s;

  ...

  server {
    ...

    location / {
      if ($uatype == 'badbot) {
        return 403;
      }

      limit_req zone=one burst=5 nodelay;
      if ($uatype != 'user') {
        limit_req zone=two burst=10 nodelay;
      }

      ...
    }

  ...
  }
}

BUT - 'if' isn't allowed to do this.
$ nginx -t
nginx: [emerg] "limit_req" directive is not allowed here in /etc/nginx/nginx.conf
nginx: configuration file /etc/nginx/nginx.conf test failed
There are so many untested suggestions on nginx forums, most do not even pass configtest.
One that looks promising is Nginx Rate Limiting by Referrer? -- Downside of that version is that all of the configuration is repeated for each different limit (I have many rewrite rules)
Anyone got something good?
Answer: Today I was able to implement rate limiting on a user agent base; try this:
map $http_user_agent $bad_bot {
    default 0;
    (foo|bar) 1;
}

map $http_user_agent $nice_bot {
    default "";
    (baz|qux) 1;
}

limit_req_zone $nice_bot zone=one:10m rate=1r/s;
limit_req_status 429;

server {
    ...
    location / {
        limit_req zone=one nodelay;
        if ($badbot) {
            return 403;
        }
        ...
    }
}

Comment: Does this limit all IPs that use the same user agent, or will it limit each IP that uses the user agent separately?
Comment: We are doing something similar, but not getting anything close to our "rate" across many IPs that are DDOSing us.
Answer: Unfortunately you can't dynamize this way, limit request module doesn't support this.
The link you found is probably the only way to achieve this. Use include directive to "avoid" repeating your configuration.
But what if a thirdparty crawler suddenly impersonate a goodbot user agent ?
Comment: > But what if a thirdparty crawler suddenly impersonate a goodbot user agent ? -- totally agree - terrible that google doesn't publish a ip list. Thanks for the answer.
Comment: @AliW Interestingly, [tengine](http://tengine.taobao.org/document/http_limit_req.html) which is the chinese fork of nginx developed by alibaba seems to have better support for these cases.
Comment: In my error.log I see a line:
2022/02/08 10:00:55 [error] 25833#25833: *150390 limiting requests, excess: 20.855 by zone "mylimit", client: 22.214.171.124, server: _, request: [MORE HERE]
How can I add the user-agent in the erorr.log print?


"Néron-Ogg-Shafarevich criterion" in positive characteristic

Question: The Néron-Ogg-Shafarevich theorem usually seems to be cited to say that an abelian variety over a finite extension $K/{Q}_p$ has good reduction at $\ell \neq p$ if and only if the associated $\ell$-adic Galois representation (Tate module) is unramified, as seen in Serre-Tate. I am aware that these conditions can be slightly generalized (cf. the Néron models book). I also know that you get the analogous result at $\ell = p$ if you replace "unramified" by "crystalline," but that this was proven much more recently.
However, from skimming the proofs of these various results, I don't immediately see where the fact that $K$ is characteristic zero is used. For instance, Serre-Tate doesn't seem to say anything about the characteristic of $K$. Nevertheless, I haven't yet seen this theorem applied when $K$ has positive characteristic, and some of the results (e.g. the Coleman-Iovita paper where it is shown if the p-adic Tate module is crystalline, then the abelian variety has good reduction) do assume that $K$ is characteristic zero (and perfect residue field, but I am less concerned about this).
I guess I have a couple of related questions:

Does the Néron-Ogg-Shafarevich theorem for abelian varieties hold when $K$ has positive characteristic? If so, could you link to a paper where it is applied in this fashion?
Can you get similar results "at $p$" when char$(K) = p > 0$?
Answer: Yes, it is true in the function field setting.  This will follow
from the Neron models argument in Serre--Tate.
Note that "crystalline" only makes sense in the mixed char. setting.
If you work directly with $p$-divisible groups (i.e. talk about the
$p$-divisible group extending over the ring of integers) then the
result should be true in the char. $p$ setting.  My feeling is that
this kind of thing would be proved in the part of SGA7 dealing with
Neron models.  (E.g. an extension of the Neron mapping to $p$-divisible
groups is proved in there somewhere, although I forget the precise
statement or hypotheses.)  I'm always made a bit nervous about non-perfect
residue fields too, so let me not commit to anything on that point, since
I'm just writing off the top of my head.


Bypass installing updates on shut-down

Question: So with the cold weather, we're experiencing rolling blackouts in industrial sectors to keep residential heaters going. Every two hours for 15 minutes, we go dead. The last couple times this happened, we had workstations running on about 30 seconds' worth of UPS power, that we were trying to shut down quickly but the workstations were insisting on getting updates.
I need a way to bypass this; when I have 30 seconds to get a computer shut down, I don't care if I have the latest recommended updates, I need it shut down NOW. Are there any tips, other than "just make sure you have all the latest updates installed already"?
Answer: To force a immediate shutdown and bypass updates install, use command line
<code>   shutdown /s
</code>
For a more permanent solution, use Group Policy Objects
<code>  gpedit.msc
</code>
Enable, on [computer\administrative templates\windows components\windows update]

Do not adjust default option to 'Install Update and Shut Down' in Shut Down Windows dialog box
Answer: Possibly STOP the Automatic Updates service first. I bet that will do it.
Windows 7 friendly name is Windows Update
Windows XP friendly name is Automatic Updates (I think)
Service name on both (if you want to run a net stop: wuauserv

Bypass installing updates on shut-down


Problemas com Group By no PostgreSQL

Question: Estou tentando fazer uma view em um banco de dados Postgre:
CREATE VIEW anuncio_points
AS
    SELECT
    a.*,
    (CASE WHEN p.points is null THEN 0 ELSE sum(p.points) END) + u.points as points
    FROM anuncios as a
    LEFT JOIN users as u ON u.id = a.user_id
    LEFT JOIN points as p ON p.user_id = u.id
    GROUP BY a.id;

Porém esta retornando o seguinte erro:
ERROR:  column "p.points" must appear in the GROUP BY clause or be used in an aggregate function
LINE 5:     (CASE WHEN p.points is null THEN 0 ELSE sum(p.points) EN...

Já pesquisei em centenas de site porém eu só encontro o comando para MySQL eu habilita/desabilita essa função:
SET sql_mode = 'ONLY_FULL_GROUP_BY';

Se for possível de resolver o erro com um comando como este ultimo qual seria o seu equivalente em PostgreSQL?
Se for algum outro tipo de erro, alguém tem alguma solução? Já perdi algumas horas nisso...
Answer: Se você utilizar o sum no p.points e no u.points soluciona seu problema, uma vez que eles não estão no group by.
CREATE VIEW anuncio_points AS SELECT
    a.*,
    ( SUM(p.points)  + SUM(u.points)) AS points
FROM
    anuncios AS a
LEFT JOIN users AS u ON
    u.id = a.user_id
LEFT JOIN points AS p ON
    p.user_id = u.id
GROUP BY
    a.id;

Problemas com Group By no PostgreSQL


Editar campo de busca com icon CSS

Question: Estou desenvolvendo uma aplicação web e gostaria de formatar meu campo de busca assim.Com icon dentro e um placeholder escrito Procurar produto

Olha como esta o meu campo de busca.

Com as bordas redondas e com icon dentro do botão e o nome Procurar um produto dentro mas não estou conseguindo.
HTML

<input type="text"id="busca">

CSS
 .campo_busca{
  margin-top: 40px;
 margin-left: 160px;
 border: 1px radius solid;
}

 #busca{
 width: 90%;
  }

Answer: O placeholder serve para exibir um texto prévio no campo:
placeholder="PROCURAR UM PRODUTO"

E você pode aplicar estilos ao input e ao botão de forma que eles fiquem como indicado na imagem. Usei também cursor: pointer no botão para que o ícone do mouse mude ao passar por cima.

*{
   position: relative;
}

.campo_busca{
   margin-top: 40px;
   margin-left: 160px;
}

#busca{
   width: 90%;
   border: 1px solid #000;
   border-radius: 5px;
   padding: 30px 30px 30px 50px;
   text-align: center;
}

.campo_busca i{
   position: absolute;
   top: 50%;
   left: 25px;
   transform: translateY(-50%);
   cursor: pointer;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

   <input placeholder="PROCURAR UM PRODUTO" type="text" id="busca">

Adicione também position: relative a todos os elementos da página, para que se possa movê-los ou posicioná-los. Inclua no CSS:
*{
   position: relative;
}

Editar campo de busca com icon CSS


Question regarding the definition of a functional

Question: I know that a functional is defined as a map
$$f : M \mapsto \mathbb{R} \tag{1}$$
or
$$f : M \mapsto \mathbb{C} \tag{2}$$
(or similar). Therefore, expressions like the following are functionals:
$$ F[y] = \int_{a}^{b} \mathrm{d}x \sqrt{1-y'^{2}(x)} \tag{3}$$
$$ G[y, y'] = \int_{x_{1}}^{x_{2}} \mathrm{d}x \frac{y^{3}(x) + y'(x) +x^{2}}{\cos(y(x))} \tag{4}$$
$$ H[y] = \exp(y^{2}(x) \delta(x-x_{0})) \tag{5}$$
because they depend on the function ($y(x)$) and its derivatives only, but not on the independent variable. Thus by plugging an implicit map $y: z \mapsto f(z)$, one gets a real number (that is how I understand it, please correct me if I am wrong).
My question regards expressions which also involve the independent variable, like
$$A[y(x)] = y(x) \sin(y(x)) \tag{6}$$
$$B[x(t)] = x(t) \int_{0}^{1} \mathrm{d}w \frac{e^{-w}}{w + t} x(w) \tag{7}$$
Can these be regarded as functionals? Are they some kind of generalised functionals?
The reason for my question is the fact that I am learning about functional derivatives. And while I have seen many examples of how to find the functional derivatives of $F, G, H$, I am not clear on how (or whether it is possible) to find the functional derivative of something like $A$ or $B$.
Comment: Both of the examples you give take as input a function and return as output another function. These are typically called *operators* or, depending on context, *transforms*; e.g. differential operators or the Fourier transform. They (potentially) have derivatives which are given by linear operators: https://en.wikipedia.org/wiki/Fr%C3%A9chet_derivative
Comment: The writing of $A$ and $B$ could be improved: $A$ takes a function and maps it to another function, so I would write
$$
(A(y))(x) = y(x) \sin(y(x)).
$$
The same is true for $B$, better to write (in my opinion)
$$
(B(x))(t) = x(t) \cdot \int_0^1 \dots dw.
$$
I put brackets around $A(y)$ and $B(x)$ to emphasize that we evaluate the functions $A(y)$ and $B(x)$ at the given points $x$ or $t$.
Comment: Thank you. Just to clarify, $A$ and $B$ are not functionals, but operators.
Answer:
"expressions like the following are functionals: [...] because they depend on the function (()) and its derivatives only, but not on the independent variable."

Thousands of people would disagree with that definition of a "functional" since the Feynman-Vernon influence functional does depend on the independent variable $t$ [see Eq. 9 of this 2012 paper or Eq. 8 of this 1995 paper]. These are just two of the many papers over a period of 6 decades that use this functional (an older paper from 1963, which has 3000+ citations on Google Scholar is this one).
In your comment, you said:

"Just to clarify,  and  are not functionals, but operators."

But no one said that an operator cannot be a functional.

"while I have seen many examples of how to find the functional derivatives of ,,, I am not clear on how (or whether it is possible) to find the functional derivative of something like  or ."

Your $A$ is a composite function. It can also be written with round brackets: $A(y(x))$ to indicate that it's an ordinary function $A(x)$ in which the argument is an ordinary function $y(x)$. Knowing $x$ is enough to give you $A(y(x))$, whereas for $B[y(x)]$ we certainly need the square brackets to indicate that we need to know all of $y(x)$ (not just $y$ at a specific value of $x$) to obtain $B$.
Your $B$ is precisely the same as the following operator in Annie Cuyt's PhD thesis, except you changed $s$ to $w$ and the numerator was changed from $t$ to $\exp(w)$. It was differentiated in her thesis as you can see below:

She used the Frechet derivative, where $L$ is the derivative (see one page earlier in the same thesis):
Answer: The idea that a map from functions to anything else could "depend on the independent variable" is quite vague and ambiguous, but I suspect I know what is intended.
If we are being careful, in modern times, a function $f$ can be defined in various ways, and, at the end of the definition, there is no "independent variable" (by any name). Yes, $f(x)$ may be expressed by a formula in terms of $x$, but the scope of this auxiliary "$x$" is limited to that definition.
For some sort of operator/functional $T$ on functions $f$, to say that $Tf$ "depends on $x$" is not literally sensible, though I can guess what is intended... Ok, the $f$'s are functions on some space, for example, the real line, and the outputs $Tf$ are also functions on the real line (as opposed to just being real or complex numbers). It's not that they "depend on the independent variable". That is a too naive description of functions, etc.
Yes, at a very introductory level, it is useful to think about "variables" and "independent variables", and such, but it is even more important to eventually discard this viewpoint, since it amounts to "painting oneself into a corner". After all, it is not true that "$x$" is any sort of sacred name for the input to a function, etc. :)


How to assess the significance of interactions between categorical variables

Question: Suppose I have a model with an interaction between two dummy variables
$$
\begin{equation}
wage = \beta_0 + \beta_1 male+ \beta_2 white + \beta_3 educ + \beta_4 (male* white) + \epsilon
\end{equation}
$$
and that the coefficient for $ \beta_4 $ is significant.
Am I able to say that the impact of being white is significantly conditioned by gender (i.e. that the coefficient for white is different across men and women)? In the case of a continuous moderator, I would plot the conditional effect of the independent variable for different values of the moderator and see whether this effect is statistically different from zero. Should I do something similar also in this case? Thanks a lot.
Comment: When variable interactions like this start being important, consider a Structural Equation Modeling (SEM) approach. Interaction terms will get the job done, but with less clarity/interpretability.
Answer: You can say both the impact of being white is significantly conditioned by gender and equally the impact of gender is significantly conditioned by being white. You can plot the distribution of $wage$ in each of the four subgroups, for instance using box-and-whisker plots, violin plot, and even scatter plots. See for example Figure R9 here: https://wellcomeopenresearch.org/articles/4-63


G# major vs Ab major in the Liszt's Les Preludes

Question: In this video at 6:21, the instructor says that

In measure 62 of Liszt Les Preludes (image below), the intonation is difficult if you think of as a "G sharp major."

Instead, it will be easier if you think of it as "A flat major."

Questions:

Why would one even think the measure 62 as a "G sharp major?"

For example, this article says Why is there no G# major key?
.

Why would it be difficult if thinking of as a "G sharp major." Why will it be easier if thinking of it as "A flat major?"

"G sharp major":
https://commons.wikimedia.org/wiki/File:Gis-dur.PNG
Comment: @1: Why wouldn't one do so? It is the most obvious choice with the notes given. And yes, there totally is a key we can call G# major. Of course one can enharmonically identify this key with Ab major **assuming a 12 pitch chromatic tonal base**. @2: People are more used to play stuff with little accidentals, so they will feel more comfortable if they think `C` than if they think `B#`.
Comment: There is no key called G sharp Major.
Answer: One would think of this measure as G♯ major because the notes literally spell the root, third, and fifth of a G♯-major chord: G♯, B♯, and D♯.
Furthermore, this is ultimately what the music has done. Les preludes begins in C, then it moves up a major third to E major. Then, this music in E major moves up another major third to G♯ major, albeit briefly.
The article you cite is a bit poorly titled. There definitely is a key of G♯ major, but seeing the key signature of G♯ major is relatively rare. So rare, in fact, that we don't even agree on how these "theoretical" key signatures should look; see Where do the double accidentals go in "theoretical" key signatures? But the logic of these keys existing is very real.
As for it being easier to think of as A♭ major, that's just a practical issue: it's easier to think in a key that only has four accidentals than one that has eight sharps spread out across only seven notes. Pitches like B♯ (the third of G♯) are pretty rare compared to something like C (the third of A♭), a pitch that string players have played thousands upon thousands of times in their lives.
Comment: Nit-picking, I know, but those 4 flats aren't accidentals. Sharps or flats in the key signature ought to have a special name, but I guess they're just - the key signature!
Comment: @Tim Yes, and I've always loved that question of yours here! But what else should I say? "A-flat has four ??? compared to G-sharp's eight."
Comment: I suppose, in the absence of a better term - 'Ab has a key sig. of 4b'. But I'm sure we agree they're certainly not accidentals! Love to find/make a better term, wouldn't you?


The certificate is not trusted because the issuer certificate is unknown. (Error code: sec_error_unknown_issuer) Firefox

Question: A website wants to switch an SSL certificate from Network Solutions to Gandi. Everything seemed to be installed correctly except that there is an error being thrown in Firefox only. On Chrome and IE, there are no errors being thrown. It appears that there is something wrong with the certification path. I've tried a few things and Googled around but the problem won't go away. Any tips would be appreciated. Thank you in advance!
Steps attempted:

Gandi Intermediate Certificate acquired from Gandi per instructions at http://wiki.gandi.net/en/ssl/intermediate (SHA2 Standard certificate)
Added the Gandi Intermediate Certificate to the server (MMC > Certificates > Intermediate Certification Authorities > Certificates)
USERTRust RSA Certification Authority Certificate acquired from SSL-Tools at https://ssl-tools.net/certificates/1y0ovx5-usertrust-rsa-certification-authority
Added the USERTrust RSA Certification Authority Certificate to the server (MMC > Certificates > Trusted Root Certification Authorities > Certificates)
Restarting IIS after every installation.
Clearing local browser cache after every installation.

Firefox Error:
Technical Details
www.somedomain.org uses an invalid security certificate.
The certificate is not trusted because the issuer certificate is unknown.
(Error code: sec_error_unknown_issuer)

Firefox 34 Certificate Heirarchy:
Gandi Standard SSL CA 2 > somedomain.org

Chrome 40 and Internet Explorer 11 Certification Path:
USERTRust > USERTrust RSA Certification Authority > Gandi Standard SSL CA 2 > somedomain.org

SSL Labs test results (https://www.ssllabs.com/ssltest/analyze.html):
Additional Certificates (if supplied)
Certificates provided   2 (2851 bytes)
Chain issues    Incomplete
#2
Subject Gandi Standard SSL CA 2
Fingerprint: 247106a405b288a46e70a0262717162d0903e734
Valid until Wed Sep 11 16:59:59 PDT 2024 (expires in 9 years and 8 months)
Key RSA 2048 bits (e 65537)
Issuer  USERTrust RSA Certification Authority
Signature algorithm SHA384withRSA

Certification Paths
1   Sent by server  somedomain.org
Fingerprint: 0123456789012345678901234567890123456789
RSA 2048 bits (e 65537) / SHA256withRSA
2   Sent by server  Gandi Standard SSL CA 2
Fingerprint: 247106a405b288a46e70a0262717162d0903e734
RSA 2048 bits (e 65537) / SHA384withRSA
3   Extra download  USERTrust RSA Certification Authority
Fingerprint: eab040689a0d805b5d6fd654fc168cff00b78be3
RSA 4096 bits (e 65537) / SHA384withRSA
4   In trust store  AddTrust External CA Root   Self-signed
Fingerprint: 02faf3e291435468607857694df5e45b68851868
RSA 2048 bits (e 65537) / SHA1withRSA
Weak or insecure signature, but no impact on root certificate

SSL-Tools test results (https://ssl-tools.net/webservers/):
Certificate chain
somedomain.org
1054 days remaining  2048 bit sha256WithRSAEncryption
- Gandi Standard SSL CA 2
- 3537 days remaining  2048 bit sha384WithRSAEncryption
- Root certificate unknown
-- USERTrust RSA Certification Authority

Server:

Windows Server 2008 R2
IIS 7.5
Answer: 'USERTrust RSA Certification Authority' is not recognized as a root CA on all platforms. So, the best option is use it as an intermediate CA, having a certificate signed by 'AddTrust External CA Root'.
You can retrieve this certificate at http://crt.usertrust.com/USERTrustRSAAddTrustCA.crt
Proper installation (most accepted) of your certificate is:

Root store

AddTrust External CA Root

Intermediate store

USERTrust RSA Certification Authority (signed by AddTrust)
Gandi Standard SSL CA 2

Personal store

[your server certificate]

Windows Server 2008 R2 manages automatically trusted certificates, so your server could get the next configuration:

Root store

AddTrust External CA Root
USERTrust RSA Certification Authority (self-signed)

Intermediate store

USERTrust RSA Certification Authority (signed by AddTrust)
Gandi Standard SSL CA 2

Personal store

[your server certificate]

When server sends the certificate it chooses the shortest path to root:

[server] < Gandi < USERTrust (self-signed)

And that is an incomplete chain for most platforms.
If this is your problem, the best solution is locate the 'USERTrust RSACertification Authority' on Root store and edit its Properties to 'Disable all purposes for this certificate'.
After you restart the server, Windows will always generate the desired chain:

[server] < Gandi < USERTrust < AddTrust
Comment: 'AddTrust External CA Root' and 'USERTrust RSA Certification Authority' are different root certificates. But 'USERTrust RSA Certification Authority' has also a certificate (with the same public key and CN) signed by AddTrust.
It's better to use the intermediate certificate of USERTrust, enabling all clients trust your certificate.
It's very important that you disable all purposes only to the 'USERTrust RSA Certification Authority' on root store.
I've edited my post to reflect that a restart of the server is needed after the changes.
Comment: I'm not sure where to put this but @mimaen's answer shows what's missing but does not say how to fix it. What helped me was to install the certificates via MMC in this order: 1) Primary Gandi SSL Certificate as PFX into the Personal store, 2) Gandi Cross-Signed Certificate into the Intermediate store, and 3) USERTrustRSAAddTrustCA.crt into the Intermediate store. I'm not sure if it's necessary, but there was a reference online that suggested removing the RSA from the root store so we did so and have not seen any problems yet with that missing certificate. Thank you for your help.
Comment: Thank you so much for the response. I took a look and it seems like all of the certificates are installed in the right places. Using the console MMC > Certificates (Local Computer) and then Personal, Trusted Root Certification Authorities, and Intermediate Certification Authorities, there are entries for all 5 certificates as you've noted. I also tried "Disable all purposes for this certificate". I'm guessing we're missing something small. Is "AddTrust External CA Root" the same as "USERTrust RSA Certification Authority"?


How google chrome debugs typescript

Question: I have some angular applications which I did built using angular CLI which has typescript files. I always did debugged them from chrome, but chrome only understands javascript, right? Does anyone know how it manages to debug typescript?
Comment: the angular cli compiles your app to js files and serves it then... when you see where the console.logs or errors or whatever come from, it's due to generated sourcemap files
Comment: write the **debugger** in code, where you want to check.
Comment: Short answer, sourcemaps.
https://stackoverflow.com/questions/44315460/when-do-browsers-download-sourcemaps
Answer: If you use Angluar with VS Code then you can use Debugger for Chrome extension to debug typescript in Chrome or any other target that supports the Chrome DevTools Protocol.

How google chrome debugs typescript


How to add new values to a custom field

Question: I can't seem to find the answer to this anywhere.
Programmatically, I need to add new values to a custom field of a new node instance I just created via API.  I am taking input via a form and want to add that data to the custom field in the new node.  I know the columns of the custom field.
How can I do that, or where is a good reference?
(the custom field type is address, if that matters)
Answer: If you are using a custom form which is invoked by a menu callback, you could try this.
Assuming that you have a postal address field type (provided by the addressfield module) which as 5 sub-fields - country, address 1, address 2, city and postal code in your content type.
/**
 * This will be invokded by a menu callback
*/
function yourmodule_custom_form($form, &$form_state){

    /* your form elements definition here */

    $form['#validate'][] = 'yourmodule_custom_form_validate';
    $form['#submit'][] = 'yourmodule_custom_form_submit';

    return $form;
}
/**
 * Validation attached to the form
*/
function yourmodule_custom_form_validate($form, &$form_state){
    // do validation here
}
/**
 * Submit handler attached to the form
*/
function yourmodule_custom_form_submit($form, &$form_state){
    global $user;
    $values = $form_state['values'];

    # Create a node object, and add node properties.
    $node = new stdClass();
    $node->type = 'your_content_type';
    $node->uid = $user->uid;
    $node->created = strtotime("now");
    $node->changed = strtotime("now");
    $node->status = 1;
    $node->comment = 0;
    $node->promote = 0;
    $node->moderate = 0;
    $node->sticky = 0;
    $node->language = LANGUAGE_NONE;

    $field_address = $values['field_address'][LANGUAGE_NONE][0];

    $node->field_address_country = $field_address['country'];
    $node->field_address_thoroughfare = $field_address['thoroughfare'];
    $node->field_address_premise = $field_address['premise'];
    $node->field_address_locality = $field_address['locality'];
    $node->field_address_postal_code = $field_address['postal_code'];

    node_object_prepare($node);
    # Save the node.
    # The node will also get published, if $node->status was set to 1.
    node_save($node);
    $nid = $node->nid;
    # if you want to redirect to a page after submission, use this
    $form_state['redirect'] = 'path/to/redirect';
    drupal_redirect_form($form_state);
}

I did not test the code. It is just for example. You may need to amend it by yourself.
You can inspect your address field name by printing out $form.
dpm($form); // if you have devel module enabled
echo '
'; print_r($form); echo '
'; // if you don't have devel moduel

Also note that when you create a new field, Drupal creates two new tables starting with field_data_field and field_revision_field. If you name the field "address", you will see two new tables field_data_field_address and field_revision_field_address, you could look up into those tables.
Comment: Sithu, I am presenting a regular form to gather the data.  How would this hook be called after the user submits the form?
Comment: I may have answered my question.  Do I use hook_form() and test the node type and call my custom form?
Comment: Are you rendering a custom form which is invoked by a menu page callback? Can you please expand your question?
Comment: Yes, it is a custom form invoked by a menu callback.  I need to do some extra validating and processing on the input data before it is added to the custom field.
Comment: I've updated my answer. Please check.
Comment: Sithu, I think that is what I'm looking for.  The addressfield field has several values in its schema.  How do I set the individual fields with their values?
Comment: I just updated my answer. I hope you are not looking for ready-made code. You could inspect `$form` and `$form_state` to know what the field names are. You can also find out in the field table, for example, **field_data_field_address**.
Answer: Sithu, thanks for your help.  That worked.  In the end, Drupal made it easier than I was thinking it would be.  I'll post my code and do a walk-through when I get some time.
Comment: Glad to hear that. But this is not an answer. You should just leave a comment.

How to add new values to a custom field


Is crossover cable still needed?

Question: Do I still need a crossover cable to connect two PC's directly? (NIC <-> NIC)?
If not, then why was this needed in the past, and when was it used for this? Specifically, when did crossover cables stop being needed to directly connect 2 PCs?
Comment: Note: Cross-over cables only applied to 10 and 100Mb Ethernet. Gigabit sends and receives on all 4 pairs at the same time.
Comment: Why is this off-topic?
Comment: @ChrisS, what you describe only applies to UTP cabling. Ethernet on fiber-optic cabling still requires a crossover cable between two like devices, even at gigabit speeds.
Answer: Most (all?) current devices have implemented ethernet auto mdix. The answer is simple: You don't need such cable.
Comment: @evachristine I remember having to use on in the 90s. I think by the early 2000s most devices were Auto MDI-X. Then 1GbE took over and made the whole thing moot.
Comment: but from when? from 10 years ago?
Comment: @evachristine there is probably no border date..
Comment: Then I will say about ~2005... according to google searches..

Is crossover cable still needed?


Suppose $Z \sim Bern(p(X))$ and $Y = \beta X$ where $X \sim N(0,1)$. Does this imply $E(ZY) = E(Y)P(Z=1)$?

Question: Suppose $Z \sim Bern(p(X))$, where $p(X)$ is a logistic function of $X$. Then let $Y = \beta X$ where $\beta$ is a constant. Then, let $X \sim N(0,1)$. Does this imply $E(ZY) = E(Y)P(Z=1) = \beta E(X) p(X)$?
In other words, in general is it true that for $Z \sim Bern(p(X))$
$$
E\left[ZY\right] = E\left[1\cdot Y\right]P(Z=1) + E\left[0\cdot Y\right]P(Z=0)
$$
?
I am a bit unsure here as we have $Y$ and $Z$ both a function of the same variable $X$. Does anyone have any ideas? thanks!
Answer: $$\mathbb{E}\left(ZY\mid X=x\right)=\mathbb{E}\left(Z\beta X\mid X=x\right)=\mathbb{E}\left(Z\beta x\mid X=x\right)=\beta x\mathbb{E}\left(Z\mid X=x\right)=\beta xP\left(x\right)$$
So: $$\mathbb{E}\left(ZY\mid X\right)=\beta XP\left(X\right)$$ and consequently:
$$\mathbb{E}ZY=\mathbb{E}\left[\mathbb{E}\left(ZY\mid X\right)\right]=\mathbb{E}\left[\beta XP\left(X\right)\right]=\beta\mathbb{E}\left[XP\left(X\right)\right]$$


How much work do DJ's do?

Question: It appears to me that most major DJ's already published their song and are replaying it with some effects during a live show. When a DJ such as Skrillex is on stage and is mixing, how much work are they actually doing?
Comment: Which type of DJs do you refer to? http://en.wikipedia.org/wiki/DJ - as electronic music producer/songwriter performing his/her music, or a guy that selects songs for a party?
Comment: @atoth Like Zedd,Skrillex and Deadmau5
Comment: I had the opportunity once to watch a very skilled DJ do a set on a radio show with nothing more than 2 turntables and a mixer.  I was very impressed with what he could do with it, swapping records, adjusting speed, manipulating the turntable with his hands for different effects.  It was obvious that it took a lot of practice.
Answer: It depends on the DJ and many variables like: his skill set, his knowledge, his work, his selection of songs, etc.
There are many different tools and techniques out there, and DJing can become as complex as you want. These are some of the things that a DJ might be doing while carving and performing a set:
Beatmatching.
In order to mix and blend two or more songs, those songs need to be at the same speed. If song X is currently playing, and its speed is 128 BPM (beats per minute), and you want to mix it with song Y that is at 127 BPM, you need first to make song Y faster, you need to make it playback at 128 BPM.
This is very simple to achieve if you DJ using software, like Aleton Live, Serato, or Traktor. You press one button, and the songs will sync automatically. It is harder with turntables (vinyl) or CD players, as you need to sync the songs manually. Doing this manually requires a lot of practice and skill.
Time sync.
Once the songs are at the same time, now they need to be in the part where you want them to be. Also, the elements need to be aligned. Two tracks that are at the same speed but not correctly aligned can sound very unpleasant. Some percussive elements like the drum bass need to sound at exactly the same time, with very small room for error.
Again, this is much more easier using software.
Harmonic mixing.
Planning and executing your DJ set using music theory. Which keys will you mix? In which order? You can make chords, scales, progressions.
There is a thread here about it: What is harmonic mixing / mix in key?
Some DJs plan their whole sets around the keys of the songs. Some ignore harmonic mixing completely.
Transitions.
When and how you mix two or more songs. Which songs/elements are you mixing? At which parts?When are you adding the songs/elements? When are you killing them? Are you using filters? Will you use effects? Will you use volume? This, along with the song selection, is what really carves a DJ style.
This can be as simple as crossfading from one song to another (even without beatmatching!) or it can be much more complex. Some transitions last several minutes, while many different songs and elements are being manipulated in different ways.
Making transitions sound good is itself an art.
Selection.
Which songs will you play? When? Why? Some DJs have a predetermined ordered set that won't change or will change a little during its execution. Other DJs have nothing but a collection of tracks, and the order is dictated by the people that are listening: do they look/sound like they want me to play something more intense? Do they seem to want something smoother?
Live acts.
Some electronic artists and DJs add live elements to their act. Guitars, drums, voice, whatever you can think of.
Conclusion.
These are by no means the only dynamics you will find on a DJ set, but it's a good introduction to "what's going on". How much work do DJ's do? Some do nothing, some do a lot, some do a lot more.
I've seen respected DJs get away with playing a pre-recorded set and acting like they are doing something.
Some DJs have very complex DJ sets conceptually, but not mechanically; like a simple setup of 3 turntables and a simple 3 channel mixer with 3 band eqs (simple mechanically, in a sense) but with many complexity in harmonic mixing, transition, selection, etc.
Some DJs have very complex DJ sets mechanically, but conceptually not as complex; like a setup of 2 or more DJs with 4 turntables connected to Traktor, plus 2 CDjs, plus virtual tracks, plus many control surfaces, two laptops, external analog and digital effects, loop stations, (etc etc etc), but there is not much happening in transitions, harmonic mixing, etc.
Some DJ's have very complex DJ sets both mechanically and conceptually.
In short:
The whole spectrum! Depends on the DJ. From nothing, to as complex as they want or can handle.
Comment: @user2981256 For the most basic stuff search for the DJ Tutor Ellaskins in Youtube. He has a huge catalog of tutorials for the beginner DJ. You might also want a copy of How to DJ Right: The Art and Science of Playing Records http://amzn.com/0802139957 (you can take a look at the book on that link). Using CD players you want to master beatmatching first, so have special attention to that.
Comment: @user2981256 If you want to DJ specifically, yes. You can DJ your own songs, you can DJ other's songs, you can do both. There are other ways for electronic music producers to play their work, though. You might also be interested in looking for Live Act alternatives, like arrays of sequencers, or non-linear DAWs (like Ableton Live's session view, or Bitwig), or live synths and drum machines (hardware or software).
Comment: Since, I use Logic Pro. I could make a song in it and then go to the booth. I'd simply add some more features add transitions, and pretty much play around with the eqs and effects?
Comment: So I'll also have to learn how to physically DJ. Do you recommend any websites that have DJ tutorials for a Pioneer DJM-800 Mixer and Pioneer CDJ-2000? It doesn't really matter if they show the specific type of equipment, but any website that has good tutorials will be great. And thanks for the informative answers :)
Comment: This comment didn't seem like an answer to me, so here is a comment from a 'DJ'. Great answer above, and I can say most the 'Big Name' DJs I know have some pre-recorded (but have backups if they lose the audience). They do also plan certain transitions at parts and practice what they hope to do, but NOTHING is set in stone. A good DJ performs for their audience and that is the key element. Having an understanding of music is important too, or your mixes will probably sound horrible. Key, BPM, and style are the most important things in my mind. Hope it helps some.
Answer: A DJ can be doing a lot more than just playing records into each other even though JCPedroza's answer explains that is already quite involved.
He's a video of a well-regarded UK DJ (well he's from New Zealand but works here):

You'll notice his hands never stop moving. I don't really know what he's doing but for instance he will typically loop a song and sample it, building up a unique composition on the fly.
Other things look sort of similar to a guitarist doing tone/volume swells - swelling the volume or the panning in time with the beat, etc.
Comment: *You'll notice his hands never stop moving. I don't really know what he's doing* - I suppose a mediocre DJ could do the same to appear that he's actually doing something, no?
Comment: The link is dead.

How much work do DJ's do?


Paypal RestAPI not firing Webhooks

Question: I'm developping a payment system which is using paypal's rest api.
So far so good, I can do payments in sandbox mode without any problems.
Now I need paypal to notify me on certain events ... which is why I wanted to use webhooks.
I create a little script which just write the received body into a text file to do some debugging. Then I did create the webhook in paypal's dev site. The Webhook simulator is working fine and the json string coming from paypal is fine. However, when I just do a payment through my site, there is no webhook. They don't seem to be called, since it doesn't show any webhook events in developer.paypal.com ...
<code>        $payer = new Payer();
    $payer->setPaymentMethod("paypal");

        $payment = new PPayment();
    $payment->setIntent("sale")
        ->setPayer($payer)
        ->setRedirectUrls($redirectUrls)
        ->setTransactions(array($transaction));
</code>
I'm using the payment method "paypal" and the "sale" intent. That should be working in theory.
Anyone any idea ? I did some research and found that the sandbox is bugged from time to time ... but this is a crucial feature that I need to test.
Hope you guys can help.
Greetings
Answer: So I found the problem:
basically you have to approve the payment before you get a notification.
What is wrong with my paypal process to receive webhook notifications?
On your return Site, you just need to send an approval and there your webhook is triggered!
Comment: this answer is so rare, it should be stated in every topic regarding paypal webhooks. It indeed requires to send payment executor in order to get PayPal webhook triggered. I will make an answer with a little code too.
Answer: As @MollocH has figure out, in order to trigger PayPal's webhooks you must approve the payment once you redirected to your website.
<code>    $payerId = // 'PayerID' from the GET query;
    $paymentId = // 'paymentId' from the GET query;

    $apiContext = // you know where to get this from
    $payment = Payment::get($paymentId, $apiContext);

    $execution = new PaymentExecution();
    $execution->setPayerId($payerId);

    try
    {
        $payment = $payment->execute($execution, $context);

        // redirect user to success message or so
    }
    catch(\Exception $error)
    {

    }
</code>

Paypal RestAPI not firing Webhooks


Jsoup Entire HTML Parsing issue

Question: I'm using Jsoup 1.7.3 and my HTML page is not getting loaded completely... Here is my code:
<code>            doc = Jsoup.connect("http://www.nfe.fazenda.gov.br/portal/disponibilidade.aspx?versao=2.00&tipoConteudo=Skeuqr8PQBY=")
                      .userAgent("Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36")
                      .maxBodySize(0)
                      .timeout(70000)
                      .get();
</code>
Even with maxBodySize set to 0, it still does not load the entire page... with timeout set to 0 as well...
Can someone help?
Joe
Comment: It loads from the start of `` to the entire `` for me. Some content is rendered with JavaScript and thus not possible to get with Jsoup. You'll need to use another library to execute the JavaScript.
Comment: define `not getting loaded completely` what part are you missing?
Answer: It is working fine for me.
As mention the Daniel, some of the content is loaded with JS so you will need to use another library as Selenium or HTMLUnit
JSoup is an HTML Parser using CSS Selectors

Jsoup Entire HTML Parsing issue


I accidently changed my display name

Question: I accidently renamed my "display name".
so is there any way i can revert to old nme within 30 days, when i googled it,
I found this : Revert a display name change within 24 hours
so if any moderators revert to my old name, i will be thankfull to them.
Comment: You want it "Baby in Magento" or "Baby in Magento 2" ?
Comment: Awesome Marius, you are express , I need "Baby in Magento".....
Comment: one more thing...you want it changed for this website only, or for all the stackexchange network? I see you take part in 8 communities
Comment: only for website enough boss......
Answer: Done. Please be more careful next time.
Comment: Sure, I always follow your words : - )

I accidently changed my display name


What are returnType and argTypes in frida new NativeFunction?

Question: Example: jstring __fastcall Java_com_yxcorp_gifshow_util_CPU_getClock(JNIEnv *env, jobject thiz, jobject arg1, jbyteArray arg2, jint arg3){.....}
var CPU_getClock = new NativeFunction(addr,returnType,argTypes)

returnType and argTypes What are they?
If the return value and the parameter of the function are other types, how can I write the corresponding returnType and argTypes?
Answer: You should have a look here: https://www.frida.re/docs/javascript-api/#nativefunction
returnType is the return type of the function you are wrapping at address addr. In your case, the Java function returns a jstring. As this is not native type, returnType value will be 'pointer'.
argTypes is an array of types corresponding to the function parameters. In your case it's probably something like ['pointer', 'pointer', 'pointer', 'pointer', 'int']. Basically, any non-native type will be a pointer.


Conversão de código está dando erro

Question: Estou tentando converter um código de C++ para C e surgiram dúvidas. O código começa assim:
#include<bits/stdc++.h>
using namespace std;

void function(int x, int y, int z,  char &teste, int *total)

Pensei de retirar o #include, o namespace std e colocar só:
#include <limits.h>
#include <stdio.h>

Está correto? Ele dá um erro por causa do &teste. Pelo que eu deveria substituir??
Já troquei todos os cout e cin. Mais adiante no código, o compilador dá um erro em um for, e diz

for loop initial declarations are only allowed in C99 mode.

Porque ele não aceita o for normalmente? Isso ocorre, por exemplo, nestas linhas:
for (int i=1; i<n; i++)
    senha[i][i] = 0;

Answer: Conversão pura e simples assim é perigosa, precisa entender o que está fazendo e todas implicações. Neste caso específico demonstrado basta trocar para ponteiro que resolverá o problema. Quebrará outras partes e terá que consertá-las. Mas novamente, não quer dizer que ficará tudo como quer. O maior problema que vejo no que quer fazer é a ingenuidade da ação em algo tão simples. Se você sabe C faça em C sem depender de conversão alguma de outra coisa.
O erro dor for é que tem que declarar a variável no início do código, mas é muito melhor configurar o compilador C para aceitar o C99 e não precisar fazer esta atrocidade.
Answer: Você terá varios problemas na conversão. o char &teste diz que a variável teste está sendo passado por referência, e C não permite esse tipo de coisa. Sendo assim você deverá converter a assinatura da função para:
void function(int x, int y, int z,  char *teste, int *total)

E todos os acessos a teste deverão ser substituidos por (*teste) (acesso a apontador).
Quanto ao erro a respeito da declaração do int i=1 dentro do for, a razão disso é que o C padrão (C89) não aceita esse tipo de declaração, apenas as versões C99 ou superior. No compilador gcc você pode usar a flag -std=c99 para especificar o uso dessa versão.

Conversão de código está dando erro


How to prove an inequality involving averages of different order statistics?

Question: Let $X$ be a continuous random variable with values ranging from 0 to 1.
Let $X_{kn}$ be the random variable representing the $k$th smallest order statistic of $n$ draws from $X$.  Note that $X_{kn}$ is not a sample, but the marginal distribution of the statistic.
I begin with a simple specific case below.  Then I will present the more complicated general case.
I need to prove:
$$
\frac12\mathbb{E}(X_{22}+ X) < \frac13\mathbb{E}(X_{24}+X_{34}+X_{44})
$$
In other words, that the average of $X$ and the max of 2 draws of $X$ is less than the average of the top 3 marginal order distributions of 4 draws of $X$.
Any help would be tremendously appreciated.
Also, the more general case is below:
Let $c$ denote some constant integer $\geq 2$.
Let $i$ denote some integer $ \geq 1$.
Prove that
$$\frac1c\mathbb{E}(X_{c^i,c^i}+ (c-1)X) < \frac1{c^{i+1}-c^i+1}\mathbb{E}\left(\sum_{k=c^i}^{c^{i+1}}X_{k,c^{i+1}}\right)
$$
And, preferably, that the magnitude of the inequality increases with $i$.
Also note:  I posted a similar problem on stats.SE last week (still unanswered).  This one is different enough to warrant its own question through.
Comment: $k$-th smallest in the sample of size $n$ is usually denoted $X_{k:n}$. The sum $\sum_{k=1}^n X_{k:n} = \sum_{i=1}^n X_i$ where $X_i$ are now i.i.d.s Thus your inequality translated into $m_{ci}/c + (1-c)/c m_1 < m_1$, where $m_k$ is a moment of order $k$ of distribution followed by $X$
Comment: No, $X_{2:2}$ is not equivalent to $X^2$ in distribution. Consider uniform. Then $X_{2:2}$ has $pdf_{X_{2:2}}(x) = 2x$, while $X^2$ has $pdf_{X^2}(x) = \frac{1}{2\sqrt{x}}$.
Comment: Thanks for the help... if I understand what you wrote, then that would imply that the right side of the inequality is the average of all the order statistics, when it is really only subset of them.  Did I misunderstand?  I also edited my question with a more specific example since the subscripts can be really hard to read.
Comment: Yes, I missed that the sum is partial, sorry. It seems like you mean to write $X_{c:i}$ instead of $X^{ci}$.
Comment: No, I meant $X^{ci}$ .  It's just that it's the equivalent of $X_{ci. ci}$ so I thought it would be simpler in the example.  In the example, $c=2$ and $i=1$ so $c^i = 2$ and $X_{22} = X^{ci} = X^2$
Comment: Oh!  I was  confusing $F(x)$ with $X$... where the cdf of $X_{22} = F(x)^2$ when the cdf of $X = F(x)$.  Ooops... will correct.
Comment: @JandR: I tried to make your post easier to read, please check that no mathematical error slipped in with my modifications. // The RHS of the inequality you want to prove in the general case is dubious because the denominator is **not** the number of terms of the sum in the numerator. Hence you might wish to replace the denominator by $c^{i+1}-c^i+1$.
Comment: @Didier -- thank you for your very nice edits, and for pointing out the error (which I fixed per your suggestion).  That is helpful to know even though this has been disproved.
Answer: I have found a counterexample to your purported inequality $\frac{1}{2} ( \mathbb{E}(X_{2:2}) + \mathbb{E}(X) ) < \frac{1}{3} ( \mathbb{E}(X_{2:4}) + \mathbb{E}(X_{3:4}) + \mathbb{E}(X_{4:4}) ) = \frac{1}{3}( 4 \mathbb{E}(X) - \mathbb{E}(X_{1:4}) $.
Consider $X$ which follows $Beta(\alpha, 2)$. Then $\mathbb{E}(X) = \frac{\alpha}{2+\alpha}$ and $\mathbb{E}(X_{2:2}) =  \frac{\alpha ( 4 \alpha+3)}{(2\alpha+1)(2\alpha+3)}$ and
$$
\mathbb{E}(X_{1:4}) = \frac{\alpha ^4 \left(6912 \alpha ^5+34810 \alpha ^4+69601 \alpha ^3+68919 \alpha
   ^2+33734 \alpha +6524\right)}{(\alpha +2) (2 \alpha +1) (2 \alpha +3) (3 \alpha
   +1) (3 \alpha +2) (3 \alpha +4) (4 \alpha +1) (4 \alpha +3) (4 \alpha +5)}
$$
With this results, your inequalities is only satisfied when $\alpha > 0.51$.
In case you find this useful, here is Mathematica code performing this computations:
<code>In[40]:= ineq =
  With[{dist =
     BetaDistribution[a,
      2]}, (Expectation[x,
        x \[Distributed] OrderDistribution[{dist, 2}, 2]] +
       Mean[dist])/2 <
    1/3 (4 Mean[dist] -
       Expectation[x,
        x \[Distributed] OrderDistribution[{dist, 4}, 1]])];

In[41]:= Reduce[ineq && a > 0, a, Reals] // N

Out[41]= a > 0.512761
</code>
Comment: Oh no!!  Thanks so much for figuring this out and pointing it out. I need to process this for a bit.  The actual distributions I need to prove it on will all be iterations on $F(x) = Max2(Min2(x))$, or $Max2(Min2(Max2(Min2(x))))$, or $Max2(Min2(Max2(Min2(Max2(Min2(x)))))$... etc.  Where $Max2(x) = x^2$ and $Min2(x) = 1-(1-x)^2$.  So my the cdfs of my $X$s will look like $(1-(1-x)^2)^2$ and $(1-(1-(1-x)^2)^2)^2$, etc.  Hopefully I can still prove it in that case....
Comment: PS, I really appreciate your answer and will vote it up if I even get enough points to be able to :)
Comment: Ok, I have added a new constraint on $X$ in the question.
Comment: @JandR: Please **DO NOT DO THAT**. Now it seems Sasha's post does not answer your question. Much better to add a paragraph **Edit** at the end of your post, describing the modified version of the question, so that the original version (to which Sasha answered) is still there for all to see.
Comment: ok.  it has benn undone.


How do I install the arrow package on RStudio Cloud with lz4 support?

Question: I have a problem similar to this RStudio community post and to this stack overflow post.
I have tried the solutions presented in both cases. I still cannot get arrow installed with lz4 support. I am trying to be able to use arrow::read_feather() which requires lz4 support.
After following the instructions in the first solution, I get the following error when trying to load the arrow package.
> library(arrow)
Error: package or namespace load failed for 'arrow' in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/home/rstudio-user/R/x86_64-pc-linux-gnu-library/4.0/arrow/libs/arrow.so':
  libcrypto.so.1.0.0: cannot open shared object file: No such file or directory

Any ideas on how to install arrow with lz4 support in RStudio Cloud?
Comment: Have you tried to install arrow with `Sys.setenv(LIBARROW_MINIMAL = FALSE); install.packages("arrow", type = "source")`? That will build arrow from source and install many of the optional extra packages. Setting `Sys.setenv(ARROW_R_DEV = TRUE)` will give you verbose output.

I've tried to replicate this on RStudio Cloud, and I am getting the same error when using RSPM binaries. Given the error that `libcrypto.so.1.0.0` can't be opened and lookintg at what libssl is installed on RStudio Cloud (libssl1.1) I suspect there's a mismatch of versions between the RSPM binary and RStudio Cloud.
Comment: @JonKeane, When I try installing with this method I get
`*** Successfully retrieved C++ source`
`*** Building C++ libraries`
`**** cmake`
`**** arrow`
`**** Error building Arrow C++. Re-run with ARROW_R_DEV=true for debug` `information.`
`------------------------- NOTE ---------------------------`
`See https://arrow.apache.org/docs/r/articles/install.html`
`for help installing Arrow C++ libraries`
`---------------------------------------------------------`
Comment: @JonKeane adding thw verbosity allowed me to finally find the error in the install. +1 !!
Answer: Thanks to the comment from @JonKeane and his answer to my jira issue
I was able to use
Sys.setenv(LIBARROW_BINARY = TRUE); install.packages('arrow', type = "source")

to solve this issue.


Required conditions for eigenvalues $\lambda_{\min}(A) >\lambda_{\min}(B)$ and $\lambda_{\max}(A) >\lambda_{\max}(B) $ etc?

Question: Given $\operatorname{tr}(X^TAX) > \operatorname{tr}(X^TBX)$ and $A$ and $B$ are p.s.d then under what conditions will we have $\lambda_{\max}(A)>\lambda_{\max}(B)$ to be guaranteed ? What are required conditions for  $\lambda_{\min}(A)>\lambda_{\min}(B)$ ? All matrix entries are real valued and $X$ is a rectangular matrix. Thirdly, what are the conditions for second smallest eigenvalue (algebraic connectivity) of $A$ to be greater than the same for $B$? Also fourthly, what are the conditions for the eigenvalues of $A$ to majorize the eigenvalues of $B$ from above, below and so forth? And by majorization I mean this mathematical property: https://en.wikipedia.org/wiki/Majorization . And finally and most important of all for me..What are the conditions w.r.t $A(X)$ and $B(X)$ for $\operatorname{tr}(X^TA(X)X) > \operatorname{tr}(X^TB(X)X)$ to be true if $A(X)$ and $B(X)$ are functions of X and matrix valued as well?
Answer: If $X$ is fixed there is little that could be said in general. If we have $$\text{tr}(X^TAX)>\text{tr}(X^TBX)$$ for all $X$, then $\lambda_k(A)>\lambda_k(B)$ for all $j$. This follows from
$$
\lambda_k(A)=\min_{\dim K=k}\max\{x^TAx:\ x\in K,\ x^Tx=1\}.
$$
For a fixed subspace $L$, we have $$\max\{x^TAx:\ x\in L,\ x^Tx=1\}>\max\{x^TBx:\ x\in L,\ x^Tx=1\},$$ since $x^TAx=\text{Tr}(X^TAX)>\text{tr}(X^TBX)=x^TBx$, where $X$ is the matrix with $x$ in the first column and zeroes elsewhere. Then
$$
\lambda_k(B)=\min_{\dim K=k}\max\{x^TBx:\ x\in K,\ x^Tx=1\}
<\max\{x^TAx:\ x\in L,\ x^Tx=1\}.$$
But now we can do this for any $L$ with $\dim L=k$, and so $\lambda_k(B)<\lambda_k(A).$

Regarding majorization: let $P(X)$ denote the projection onto the diagonal (or "pinching"), i.e. $P(X)$ is the matrix with diagonal $X_{11},\ldots,X_{nn}$ and zeroes elsewhere. Then we have, thanks to the Schur-Horn theorem:

The following statements are equivalent:

$\lambda(B)\prec\lambda(A)$
There exist unitaries $U,V$ such that $B=VP(UAU^*)V^*$.

Regarding your last question, "functions of $X$" is extremely vague, so I don't think that any conclusion can be drawn.


React - Quando tento usar dados vindo da API utilizando useEffect e useState, a aplicação não lê os dados no return do componente

Question: Estou consumindo a API da Deezer, utilizando useEffect e useState no ReactJS para listar determinada track (um exemplo), porém quando utilizo o .map, para renderizar, é retornado o seguinte erro:
TypeError: musicas.map is not a function

Depois de pesquisar, achei que fosse pela assincronicidade e o componente estava sendo renderizado antes de chegar os dados, porém estou utilizando async await para consumir a API.
Código:

import React from 'react';

import { Container } from '../../styles/GlobalStyles';
import { CardContainer } from './styled';
import axios from '../../services/axios';

export default function Home() {
  const [musicas, setMusicas] = React.useState([]);

  async function getData() {
    const response = await axios.get('/track/3135556');
    setMusicas(response.data);
  }

  React.useEffect(() => {
    getData();
  }, []);

  React.useEffect(() => {}, [musicas]);

  if (musicas.length === 0) {
    return (
      <Container>

Carregando

      </Container>
    );
  }

  return (
    <Container>

Home

      {musicas.map((musica) => (
        <CardContainer key={String(musica.id)}>{musica.title}</CardContainer>
      ))}
    </Container>
  );
}

Quando comento a parte do código que está listando (.map), e dou um console.log(musicas), no useEffect, ele retorna para mim os dados normalmente no console, logo o endereço da API está correto e ele está chegando os dados.
React.useEffect(() => {console.log(musicas)}, [musicas]);

Tentei listar com e sem o if (musicas.length === 0), mas dá o mesmo erro.
Creio que apesar do assync await, o componente esteja requerendo os dados antes de terem chegado, se for isso, não sei como resolver. Se alguém souber como resolver o que seja que esteja causando isso, agradeço desde já.
Comment: não é um array é um objeto simples!
Comment: @GabrielJosédeOliveira deu certo. Então, eu tava fazendo apenas como um exemplo pra facilitar quando eu fosse chamar no ```.map```.  No caso realmente é um só uma faixa, apenas queria fosse renderizado algo, mas cara, apesar de ser uma resolução muito simples, funcionou, muito obrigado.
Comment: Como a resposta da API é um objeto acredito que isso resolveria o problema `setMusicas([response.data]);` mas você tem certeza que esta batendo a request no endpoint correto? me parece que você esta buscando os dados de apenas uma musica ao invés de receber uma lista com varias.
Answer: Tem um probleminha no React, em que ele tenta renderizar TUDO e depois ir montando os componentes ao poucos, e nesse renderizar tudo da esses erros.
Faça o seguinte na parte
 {musicas.map((musica) => (
    <CardContainer key={String(musica.id)}>{musica.title}</CardContainer>
  ))}

faça o seguinte
{musicas && musicas.map((musica) => (
    <CardContainer key={String(musica.id)}>{musica.title}</CardContainer>
  ))}

ou
{musicas ? musicas.map((musica) => (
    <CardContainer key={String(musica.id)}>{musica.title}</CardContainer>
  )) : (
 Teste
)}

Ve se resolve o seu caso.
Comment: Muito obrigado pela informação, mas meu erro estava quando eu ia setar o ```reponse.data```, no caso teria que ser ```[response.data]```


View Rewrite results Inline CSS for Newletter

Question: I am trying to send a HTML newsletter with the simplenews plugin using views.
The mailing of HTML via the plugin works flawlessly (after tinkering). I included a View via the Twig Tweak plugin inside the corresponding twig template.
My main problem is very similar to this but for Drupal 8. HTML mails require (as far as I know) inline CSS to be displayed correctly in the majority of mail clients. As I use a View, inline CSS get stripped away ("sanititzed" for security I guess).
Is there any possibility for me to use Views with inline CSS as in Drupal 8 I couldn't find the correct line of code to disable this "sanitisation"?
Answer: I've been looking into this problem myself for several days, and my conclusion after going through the views code is that views is absolutely dead-set on sanitizing certain data (specifically twig template fields for custom field rewriting) not even writing your own templates can fix that.
Ultimately, my work around for this was to use Display Suite to build a custom display for my node type (which lets me use tokens in custom display suite fields) and then telling views setting up views to output Display Suite content instead of Fields.


Dependency conflict between angulartics2 and rxjs

Question: I have the following dependencies in my package.json :
"dependencies": {
 "@angular/animations": "~12.1.0",
 "@angular/common": "~12.1.0",
 "@angular/compiler": "~12.1.0",
 "@angular/core": "~12.1.0",
 "angulartics2": "^11.0.0",
 "rxjs": "~6.6.0",
 "zone.js": "~0.11.4"
},
"devDependencies": {
 "@angular/cli": "~12.1.4",
 "@angular/compiler-cli": "~12.1.0",
 "tslint": "~6.1.3",
 "typescript": "~4.3.2"
}

According to this gist, Angular 12.1.x is only compatible with rxjs 6.5.x/6.6.x
And according to the angulartics npm page, I should use angulartics 11.0.0 for Angular 12.x.
But when I launch my npm install I got the following error :
npm ERR! Could not resolve dependency:
npm ERR! peer rxjs@"^7.0.0" from email@example.com
npm ERR! node_modules/angulartics2
npm ERR!   angulartics2@"^11.0.0" from the root project

So basically it is expecting rxj@^7.0.0, but it's not compatible with my Angular version.
What are my best options ?
Answer: I think the best option is to updated to angular v13 (or v14) and use the latest version of angulartics and the latest version of RxJS.
updating angular to the lastest versions has benefits ;)
Comment: idk if that would make a big difference... otherwise you can use an older version of angulartics2 or fork the Project and correct the code in order to allow RxJS 6
Comment: It is a quite large project in my company. I can't update to major versions for this project. But i can try to upgrade to the minor version 12.2. Should I use `ng update` ?


How does Wordpress handle URLs?

Question: I encountered this (to me) unfamilliar behavior in Wordpress.
Consider a random site using WordPress with a page called example with no content. This is just a page type post and not a category, tag or any sort of hierarchy. A 404 error is triggered if I append characters after the last "/":
http://example.com/example/abc
I expect that but if I only type numbers after the final "/" no 404 error is triggered. For example loading:
http://example.com/example/1123456
gets me to example page and the numbers are kept in the URL. The numbers have no special meaning in this case. There could be any nuber there, but I would expect it to trigger a 404 as it does on other sites.
Appending numbers to the URL on index or category pages still seems to trigger a 404, but not on posts and pages.
I am wondering wether this is an actual feature of WordPress and if so, then what is its purpose?
Comment: what you are using is pretty permalinks consult this page https://codex.wordpress.org/Using_Permalinks
Comment: What is  `EXTRA_CHARACTERS `? Page/Post/Category?
Comment: @HelpingHands Its actually just characters. So if I type characters after the page slug/name in the url I get 404, but if I type numbers I get directed to the actual page with numbers left in the URL
Comment: that number is id of page/post?
Comment: @HelpingHands Yes its an Id of a post. But the question is general: If I go to a url of a page with numbers appended to it, will I always get to the page that the url (without the numbers) leads to? Appending characters causes 404, but appending numbers does not. I have tested this on multiple pages that use Wordpress and it always seems to be the case, that appending numbers to a page url does not seem to cause 404 and still leads to the page itself.
Comment: Actually wordpress generates unique id for each post, it is all about permalink. When your permalink set to default then URL will be like `www.example.com/id=10` and if you set any custom permalink then it will be as per that settings. You are getting 404 because your permalink structure is not set to custom of `Post Name` , Also to apply this setting you will need to allow it via .htaccess with   `mod_rewrite`
Comment: @HelpingHands Right, but in that case should I not be getting a 404 regardless? My permalink setting now is "post-name". I append the number to a URL leading to a page post-type page to be specific. I do not get 404 regardless of what number I enter- even something like 1234568 which does not match any post id for certain as I only have 6 posts on the site now.
Comment: then it should give you 404 , try in another browser , may be some caching issue.
Comment: @HelpingHands Well- tried it on Chrome, Mozilla and Explorer on 3 different Wordpress sites. Results: If you append /[some_numbers] to a page post-type page you dont seem to trigger 404.
Comment: Then I think you will need to define rule manually via htaccess
Comment: @HelpingHands The thing is I won't- I want to exploit this so that I can display correct images if a user enters the page with that url. Thank you for the help
Answer: This is as designed.  Wordpress matches URL's through the built-in rewrite module.  You can read about it here.  In addition, the source code to follow what is happening with this process is located in wp-content/class-wp-rewrite.php.
The specific line that provides the behavior you are seeing is below.
[(.?.+?)(?:/([0-9]+))?/?$] => index.php?pagename=$matches[1]&page=$matches[2]

This code will match on page/post-name, and any following number (this supports pagination).  However, it will not match on non-characters after the post name.  What is interesting is that even if the post does not have the specified page, it will still accept as legit.
Answer: As we all knew that WordPress works through built-in rewrite module. So it will also give you Permalinks feature for all your post you can set your permalinks through it. Let's Check out the detail here about Permalinks through WordPress based blog. Here we go with the link http://codex.wordpress.org/Introduction_to_Blogging#Pretty_Permalinks
If you want to restructure your all the URL then you need to edit this file.
$permalink_structure

The permalink structure as in the database. This is what you set on the Permalink Options page, and includes 'tags' like %year%, %month% and %post_id%.
For more detail about the permalink structure you can go through this link.
http://codex.wordpress.org/Class_Reference/WP_Rewrite
Answer: Yes, it'd an odd one, but possibly by design.
http://ww.example.com/mypage/ 200 (expected)
http://ww.example.com/mypage/idontexist 404 (expected)
But:
http://ww.example.com/mypage/0000 200 (unexpected)
I think it may have to do with how WP works with archive ID's and dates as part of the permalink structure / rewrites.

How does Wordpress handle URLs?


Creating a filter of content types?

Question: I have a content type called college facilities. This displays ALL the college facilities that are added. I would like to create more content types called:

Services
Food
College Supplies
Other

I was wondering is it possible to create a drop down filter on the college facilities page so that if a user select all then all of them are displayed or Food then only food content types are displayed?

This is what I would like it to look like with ALL being pre selected.
Is this possible?
I apologize I am very new to drupal and Im using Drupal 7.
Answer: If I understand correctly, you need to create Views page where you add exposed filter on the content types.
This is how you create an exposed filter
https://www.youtube.com/watch?v=2Yk6rre3vi8
If that is unclear for you, I will make a screenshot.
Regards,
Oleg

Creating a filter of content types?


JPA @OneToMany not fetching the childern

Question: Following is the table structure:
desc customer_survey
Name        Null     Type
----------- -------- ------------
SURVEYID    NOT NULL VARCHAR2(10)
CUSTNO      NOT NULL VARCHAR2(10)
SRNO                 NUMBER(10)
AVGRATINGS           NUMBER(5,2)
COMMENTS             VARCHAR2(50)
SENTON               DATE
RESPONDEDON          DATE

desc Survey_response
Name             Null     Type
---------------- -------- ------------
SURVEYRESPONSEID NOT NULL NUMBER(10)
RATINGS          NOT NULL NUMBER(2)
QNO              NOT NULL VARCHAR2(10)
SURVEYID         NOT NULL VARCHAR2(10)

Java classes:
 public class CustomerSurvey implements Serializable {

@OneToMany(fetch=FetchType.EAGER, mappedBy="customerSurvey",
     cascade=CascadeType.ALL)
private Set<SurveyResponse> responses;
 ......

 public class SurveyResponse {

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="SURVEYID", referencedColumnName="surveyId")
private CustomerSurvey customerSurvey;

 ......

Client code:
 List<CustomerSurvey> surveys = workService.getSurveysByCustomer("testCNo2");
 System.out.println("surveys size = " + surveys.size());

 for(CustomerSurvey survey: surveys) {
System.out.println("getting responses from the survey object now..");
Set<SurveyResponse> responses = survey.getResponses();
System.out.println("responses size= .." + responses.size());
 }

console shows:
surveys size = 1
   getting responses from the survey object now..
   responses size= ..0
whereas there are 7 responses in the DB for the selected survey.
Answer: Enable logging and look if the SQL is correct.
It is hard to tell from your incomplete code, but in general a OneToMany should not use a JoinColumn it should use a mappedBy, and the join column in the ManyToOne should reference the Id of the object.
Also ensure you are setting both sides of the relationship when you insert your objects.
Comment: I changed my code as per your comment. query in log file shows: SELECT 'com.ge.dsp.iwork.entity.CustomerSurvey' AS NUCLEUS_TYPE,SURVEY.AVGRATINGS,SURVEY.COMMENTS,B0.CITY,B0.COMPANYNAME,B0.CUSTNO,B0.EMAIL,B0.FIRSTNAME,B0.GENDER,B0.LASTNAME,B0.MIDINIT,B0.PHONE,B0."STATE",B0.STREETADDRESS,B0.TITLE,B0.ZIPCODE,SURVEY.RESPONDEDON,SURVEY.SENTON,C0.CUSTNO,C0.DATECREATED,C0.DATEUPDATED,C0.DESCRIPTION,C0.SRNO,C0.STATUS,SURVEY.SURVEYID FROM CUSTOMER_SURVEY SURVEY INNER JOIN CUSTOMER B0 ON SURVEY.CUSTNO = B0.CUSTNO LEFT OUTER JOIN SERVICE_REQUEST C0 ON SURVEY.SRNO = C0.SRNO WHERE B0.CUSTNO = <'testCNo2'>
Answer: Another option is to populate the relationship with a jpql fetch query:
"select survey from Surveys survey join fetch survey.responses"
I had the same problem and still can't find out what is going wrong. In my case the parent entity was loaded by a jpql query, and so extending this provided a workaround
Comment: It helps me. Probably the page https://en.wikibooks.org/wiki/Java_Persistence/Querying can help somebody in future
Comment: I faced w/ another issue regarding this solution, mentioned in my previous comment:    Duplicate Data and Huge Joins
One issue with join fetching is that duplicate data can be returned. For example consider join fetching an Employee's phoneNumbers relationship. If each Employee has 3 Phone objects in its phoneNumbers collection, the join will require to bring back n*3 rows. As there are 3 phone rows for each employee row, the employee row will be duplicated 3 times.
One alternative solution to join fetch that does not suffer from duplicate data is using Batch Fetching.
Answer: this link helped.
I set the collection back to lazy. And
Inside persistence class, within transaction after getting the resultset, I am now calling getResponses as:
List<CustomerSurvey> surveys = query.getResultList();
for (CustomerSurvey survey : surveys) {
    Set<SurveyResponse> responses = survey.getResponses();
}

that populates the responses.


What does "1 x Tacet" mean?

Question: What does 1x Tacet mean?

Does it mean "play the following in 1st round only"?
Comment: A more conventional way to write this would be ( 2nd X only ) instead, unless there are 3rd, 4th, 5th endings or something along those lines.
Answer: "Tacet" is a Latin musical term meaning (literally) "it is silent". in this case, the number preceding it identifies which repetitions it is to be silent for. Here, the first time through is to be silent. The second time through, do play that segment.
In jazz and other more 'modern' genres, tacet is often used for very short breaks (such as one or two bars). In classical and orchestral music, it is usually reserved for longer breaks (such as entire movements).
Comment: In jazz etc. Tacet is often used to indicate a few beats where everyone (or maybe just all of the rhythm section) stops playing.  But it's equally commonly  used as in the example above (which would have been clearer had there been some notes - it's hard to tell if you're taceting or not during a rest!)  As stated, "1x Tacet" over a repeated section is equivalent to "Play 2nd X only".

What does "1 x Tacet" mean?


Programa não executa nada quando entra em função

Question: Meu programa executa, mas logo após pedir o valor prob() o .exe para de funcionar.
Achava que era algum problema de comunicação entre funções por conta da matriz lattice[][4] como argumento, mas já procurei, ajeitei e continua acontecendo a mesma coisa. Tenho quase certeza que o problema está na comunicação entre a main() e a label().
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int random();
float prob();
int label(float lattice[][4],float);
int i, j;

int random()   /* Sorteia um número entre de 0 a 1 */
{
    float x;
    srand((unsigned)time(NULL));
    x = rand()%100+1;
    x = x/100;
    return x;
}

float prob()
{
    float p;
    printf("Probabilidade: ");
    scanf("%f", &p);
    return p;
}

int label(float lattice[][4], float p)
{

for(i=0; i<4 ; i++)
    for(j=0; j<4; i++)
    {
        lattice[i][j] = random();
    }

for(i=0; i<4; i++)
    for(j=0; j<4; j++)
    {
        if(lattice[i][j] <= p)
            lattice[i][j] = 1;
        else
            lattice[i][j] = 0;
    }
return 0;
}

int main()
{
     float lattice[4][4];
     float p = prob();
     label(lattice, p);
     system("pause");
     return 0;
}

Comment: Dá algum erro? Edite e coloque os `include`s ou algo mais que o código tenha. http://pt.stackoverflow.com/help/mcve. De ccara eu vi que seu código nem compila.
Comment: não tinha colocado completo, porque o resto tá tudo de boa, o negócio é a main() e a label(). Mas taí, o código completo...
Comment: Rapaz, ta compilando aqui. Mas como disse, o .exe trava depois de pedir a ''Probabilidade: ''...
Comment: Você debugou? Ele trava onde exatamente dentro da função `prob`? Seria no `scanf`? O travamento é consistente (isto é, sempre ocorre)?
Answer: O erro é que você está incrementando o segundo laço com a variável errada:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int random() {
    float x;
    srand((unsigned)time(NULL));
    x = rand() % 100 + 1;
    x = x / 100;
    return x;
}

float prob() {
    float p;
    printf("Probabilidade: ");
    scanf("%f", &p);
    return p;
}

int label(float lattice[][4], float p) {
    for (int i = 0; i < 4 ; i++)
        for (int j = 0; j < 4; j++) lattice[i][j] = random();
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++) {
            if (lattice[i][j] <= p) lattice[i][j] = 1;
            else lattice[i][j] = 0;
        }
    return 0;
}

int main() {
    float lattice[4][4];
    float p = prob();
    label(lattice, p);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que eu melhorei um pouco o código. Ainda seria legal usar chaves mesmo onde não precisa. Até mesmo porque já usa em alguns lugares, então mantenha a consistência. Isto é muito importante em programação.
Quando é assim, vai isolando o problema, vai mandando imprimir o valor das variáveis passo a passo ou use uma ferramenta de debug que vai mostrando para você. Vendo o programa executar é a forma de achar o problema. Foi basicamente o que eu fiz para achar o problema, por isso eu precisava do código em condições de compilar.
Comment: :) Outras coisinhas Higor: 1) bem vindo ao SOPT. 2) Se ainda não o fez, faça o [tour] e leia a [help]. Vai te ajudar muito no uso da comunidade.
Comment: Bem observado. O AP não devia levar a mal este comentário, mas executar uma depuração ajuda muitíssimo a encontrar esse tipo de problema. Eis uma oportunidade de aprender com os erros. :)
Comment: Depurar é umas das melhores maneiras de aprender. Escutar os mais experientes é outra :)
Comment: Poxa, era só isso mesmo ... Valeu, execução em ordem agora.
Comment: Depuração. Anotado. :D
Comment: Valeu pessoal, site muito útil. ;)


why my code doesn't change the head value in c# or i have to use somethings like pointers?

Question: ok, guys, so I was doing the ReplaceWord problems from leetcode in c# ! and I had to initialize a prefix tree. the reason why I use c# that because it has split method which c++ doesn't have.the problem happened when I'm done inserting a word into the trie. usually, when I use c++ and manage the pointer, the tmp will change the last Node.end from false to true. But in c# , the Node of tmp is different from the head, so when I try to change the value of the tmp , the head doesn't affect!. is there any way for me to implement a trie ? without using pointers in c#?
notes: sorry for my bad English, this is the first time I post sth on stack <3
<code>public struct Node
    {
        public char val;
        public bool end;
        public Dictionary<char, Node> children;
        public Node(char val)
        {
            this.val = val;
            end = false;
            children = new Dictionary<char, Node>();
        }
    }

public class Solution
    {

        public string ReplaceWords(IList<string> dictionary, string sentence)
        {
           //implement trie
            Node head = new Node('a');
            foreach (var word in dictionary)
            {
                Node tmp = head;
                for (int i=0;i<word.Length;i++)
                {
                    char charact = word[i];
                    if (!tmp.children.ContainsKey(charact))
                    {
                        Node NEW = new Node(charact);
                        // if(i==word.Length-1)
                        // {
                        //     NEW.end = true;
                        // }

                        tmp.children.Add(charact, NEW);
                    }
                    tmp = tmp.children[charact];
                }
                tmp.end=true;
                // why does this not effect the head end value ?
            }
            string res = "";
            string[] words = sentence.Split(' ');
            for (int i=0;i<words.Length;i++)
            {
                string word=words[i];
                Node travel = head;
                string tmp = "";
                foreach (var charact in word)
                {
                    if (travel.children.ContainsKey(charact))
                    {
                        tmp += charact;
                        travel = travel.children[charact];
                    }
                    else
                    {
                        tmp = word;
                        break;
                    }

                    if (travel.end == true) break;
                }

                res += tmp;
                if(i!=words.Length-1)
                res += " ";
            }
            return res;
        }
    }
</code>
Comment: I suspect you should read https://jonskeet.uk/csharp/references.html - you need to understand the difference between value types and reference types. `Node` is a value type - a struct.
Comment: thank you Jon Skeet for giving the solution, I just can simply change the word struct into class, and then boom, the problem has been solved. no need to change to c++ or use  pointer
Comment: More important than solving this specific problem is understanding the difference for the future. The difference between value types and reference types is *absolutely fundamental* to working effectively in C#.
Answer: Try following :
<code>        public string ReplaceWords(IList<string> dictionary, string sentence)
        {
            Node head = null;
            Node tmp = null;

            foreach (var word in dictionary)
            {
                for (int i=0;i<word.Length;i++)
                {
                    char charact = word[i];
                    if (!tmp.children.ContainsKey(charact))
                    {
                        Node NEW = new Node(charact);
                        if(head == null)
                        {
                           head = NEW;
                        }
                        else
                        {
                           tmp.next = NEW;
                        }
                        tmp = NEW;
                    }
                    tmp = tmp.children[charact];
                }
            }
            tmp.end = true;
          }
</code>


Android switch off SwitchPreference programmatically

Question: Is there a way to switch off a SwitchPreference programmatically? I tried using setEnabled(false) but that just disables the SwitchPreference, but the switch stays in the on position.
Is there a method to disable the switch programmatically so it goes back to the off position?
Answer: setEnabled as you say is to enable/disable the actual switch.
To turn it on/off programmatically try setChecked(true) / setChecked(false): http://developer.android.com/reference/android/preference/TwoStatePreference.html#setChecked(boolean)


What is the probability that at least one head is obtained from the unbiased coin?

Question: A loaded die is tossed once; if N is the result of the toss, then $P$($N = i$) = $p_i$
,
$i = 1, ..., 6$. If $N = i$, an unbiased coin is tossed independently i times.
What is the probability that at least one head is obtained from the unbiased
coin? Given that at least one head is obtained, what is the probability that N
will be odd?
I know that a loaded die has probabilities 1/21, 2/21,3/21, 4/21, 5/21, 6/21 of showing 1,2,3,4,5,6. But, I am confused as to what $p_i$ is.
Comment: This is not correct -  "a loaded die has probabilities 1/21, 2/21,3/21, 4/21, 5/21, 6/21 ".  Loaded just means not equal probility.  Here $P(N=i)=p_1$, $P(N=i)=p_2$ and so on, where the values of $p_i$ are left as variables in the problem.  Of course, they have to add up to 1.
Comment: So, apart from that, is the question clear to you and you know how to proceed?
Answer: You just compute it.  If the die shows $4$, you flip four coins and have $\frac {15}{16}$ chance of getting at least one head.  Multiply that by $\frac 4{21}$ and add all the others.
Answer:
I know that a loaded die has probabilities 1/21, 2/21,3/21, 4/21, 5/21, 6/21 of showing 1,2,3,4,5,6. But, I am confused as to what $p_i$ is.

Well now, $p_i$ is the probability that a roll of the biased dice shows face $i$.
It you have been told that these are the probabilities for your loaded die, then they are the six $(p_i)$ values.   However, if you have not been told so, then you cannot just presume it, and must leave the values as variables.
Now, you know that the probability for at least one head showing among $i$ tosses of an unbiased coin will be: $\mathsf P(H>0\mid N=i)=$ /////.
Where $H$ is of course the count for heads among the tosses of the unbiased coin.
Then, by the Law of Total Probability: $\mathsf P(H>0) = \sum_{i=1}^6 p_i \mathsf P(H>0\mid N=i) = $ /////.
Finally find $\mathsf P(N\in\{1,3,5\}\mid H>0)$ using the definition of conditional probability.
Divide and calculate.
Answer:
If you flip an unbiased coin $k$ times, the chance of getting only tails is $\frac{1}{2^k}$, so the chance of getting heads at least once is $1-\frac{1}{2^k}$.
According to the way your die is biased, you have a $\frac{1}{21}$ chance of flipping one coin, $\frac{2}{21}$ of flipping two coins, etc.
Therefore, your probability of getting at least one heads is:
$$\sum_{k=1}^6\frac{k}{21}(1-\frac{1}{2^k})=\frac{1}{21}\frac{1}{2}+\frac{2}{21}\frac{3}{4}+\frac{3}{21}\frac{7}{8}+\frac{4}{21}\frac{15}{16}+\frac{5}{21}\frac{31}{32}+\frac{6}{21}\frac{63}{64}=\frac{51}{56}$$


Razor Page Redirect to Razor Component

Question: I have the following setup in my project:
/Pages/Page1.razor
/Pages/Page2.cshtml

Page 1 is a Blazor component.
Page 2 is a Razor Page.
At the top of Page1:
@page "/Page1"

In the Page2.cshtml.cs code-behind I have:
public IActionResult OnPostAddNew()
{
    return RedirectToPage("Page1");
}

I have tried everything I can think of but I always get:

InvalidOperationException: No page named 'Page1' matches the supplied
  values.

I appreciate that Page1 is not technically a page but I haven't been able to figure out how to redirect. A NavLink works just fine to find Page1.
Comment: Is your project a Blazor one or a Razor Pages App ?You can't mix a Blazor Component Page with a Razor Page the way you do... You can't navigate from a Razor page to a Blazor one by redirection. What are you trying to do ?
Comment: Basically that. It is a Blazor Server App. I added a Razor Page to it to display a grid component. I want to navigate from that to a .razor page that displays the details.
Comment: Clarification third party grid control not grid component.
Comment: I don't think you can do it. However, you can create a Razor pages app in which you may have a page in which you can embed a Razor component to display data provided to it by the razor page...
Comment: Yah - the issue I had there was that the bindings were lost. I passed an object to the component and the NotifyProperty changed events stopped firing. The control layout (placement and size) even looked different (component vs. component embedded on a razor page). Hopefully they find a way for the two page types to talk to each other.
Answer: I was having the same problem redirecting off my Logout page.  Just using Redirect instead of RedirectToPage worked for me.  RedirectToPage got me the same error as you.  In my example the "Counter" page is Counter.razor page in the sample code you get when create a Blazor project in Visual Studio.
public async Task<IActionResult> OnGet()
{
    await _signInManager.SignOutAsync();
    return Redirect("~/Counter");
}

LocalRedirect also appears to work:
return LocalRedirect(Url.Content("~/Counter"));

Razor Page Redirect to Razor Component