Flutter - New Project - able to run flutter app on iPhone but not able to run ios app on simulator iPhone 15 Pro Max

Question: Error (Xcode): Target debug_unpack_ios failed: Exception: Binary /Users/fathom/Documents/Documents/Flutter/projects_bitbucket/flashwave/build/ios/Debug-iphonesimulator/Flutter.framework/Flutter does not exist, cannot thin
Could not build the application for the simulator.
Error launching application on iPhone 15 Pro Max.
Xcode - Version 15.0.1 (15A507)
Answer: You have to reinstall flutter.
I had the same issue after the macOS update.
Comment: Thank you for the answer, I update flutter version and dart version after the macOS update, now its working fine.


Find the matrix T relative to the standard basis $P_2$

Question: Let $$T: P_2 \to P_2$$
Such that $$T(a_0 + a_1x + a_2x^2) = a_0 + a_1(x + 2) + a_2(x + 2)^2$$
Find the matrix $T$ relative to the standard basis $B$ for $P_2$: $$B = \{1, x, x^2\}$$
I understand the procedure for finding the matrix $T$, but how exactly do the vectors of $B$ plug into the equation? i.e $$T(1) = ?$$ $$T(x) = ?$$ $$T(x^2) = ?$$
Do we treat in the first example $a_0 = 1$ and in the second equation $a_1 = x$ and $a_3 = x^2$ in the last example?
Comment: The $a$'s are the *coefficients* of powers of $x$ in the polynomial.
Answer: I imagine the result should be as follows, but I'm not sure?
$$T(1) = 0$$
$$T(x) = x + 2$$
$$T(x^2)= (x + 2)^2 = 4 + 4x + x^2$$
Which produces the matrix:
$$ [T]_\beta
\begin{bmatrix}
0 & 2 & 4 \\
0 & 1 & 4 \\
0 & 0 & 1 \\
\end{bmatrix}
$$
Am I on the right track?
Comment: $T(1) = T(a_0) = a_0$, where $a_0 = 1$, so...
Comment: And $T(x) = T(a_1x) = x + 2$ where $a_1 = 1$? And $T(x^2) = T(a_2x^2) = 4 + 4x + x^2$ where $a_2 = 1$?


jQuery: .val() em elemento select só retorna o value do primeiro option

Question: Tenho um elemento select na minha página html (código abaixo):

Calculando Para Diarista Por Hora

Calcule o valor do serviço de acordo com a quantidade de horas que a profissional trabalhará e a frequência que deseja o serviço.

    <form>

            <select id="horas">
                <option value="0">- HORAS H -</option>
                <option value="4">4 horas</option>
                <option value="6">6 horas</option>
                <option value="8">8 horas</option>
            </select>

            <select id="frequencia">
                <option value="0">- FREQUÊNCIA -</option>
                <option value="avulso">Avulso</option>
                <option value="1">1x por semana</option>
                <option value="2">2x por semana</option>
                <option value="3">3x por semana</option>
                <option value="mais3">Mais de 3x por semana</option>
            </select>

                Calcular

    </form>

E estou tentando usar pegar o valor do atributo value do option selecionado pelo usuário, da seguinte maneira:
var tempoPh = $('#horas').val();
var freqPh = $("#frequencia").val();

$("#calc-ph-bt").click(function() {
    alert(tempoPh);
    alert(freqPh);
});

Mas o valor retornado é sempre o value do primeiro option, "0", mesmo que outro option esteja selecionado. Alguém sabe como posso corrigir isso?
Answer: Quando corres estas duas linhas de código:
var tempoPh = $('#horas').val();
var freqPh = $("#frequencia").val();

as variáveis vão receber o valor do select no momento. Mais tarde quando corrers as outras linhas
$("#calc-ph-bt").click(function(){
    alert(tempoPh);
    alert(freqPh);
});

o que esses alert te vão devolver é o valor que tinham guardado antes. Isso é diferente de guardar uma referência ao elemento na variável e, dentro desse .click() "pedir" de novo o valor com .val().
Presumo que o que queres é:
var tempoPh = $('#horas');
var freqPh = $("#frequencia");

$("#calc-ph-bt").click(function(){
    alert(tempoPh.val());
    alert(freqPh.val());
});

Um exemplo com o teu HTML seria assim:

var componentes = $('#horas, #frequencia').get();
$("#calc-ph-bt").click(function() {
  const total = Number(componentes[0].value || 0) * Number(componentes[1].value || 0);
  alert(total);
});

Calculando Para Diarista Por Hora

Calcule o valor do serviço de acordo com a quantidade de horas que a profissional trabalhará e a frequência que deseja o serviço.

    <form>

        <select id="horas">
          <option value="0">- HORAS H -</option>
          <option value="4">4 horas</option>
          <option value="6">6 horas</option>
          <option value="8">8 horas</option>
        </select>

        <select id="frequencia">
          <option value="0">- FREQUÊNCIA -</option>
          <option value="avulso">Avulso</option>
          <option value="1">1x por semana</option>
          <option value="2">2x por semana</option>
          <option value="3">3x por semana</option>
          <option value="mais3">Mais de 3x por semana</option>
        </select>

          Calcular

    </form>

Answer:

<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>

</select>


Appropriate way to model nested random effect structure with lme4

Question: Let's say I have data on firms (nested within countries).  Some firms are multinational, others only have a single instance. The dependent variable is revenue.  What is the appropriate way to account for the clustering structure of this relationship?
If using a mixed effects approach, my intuition is to treat country-firmID as a nested random effect like so (1| country/FirmID)
lmer(log_revenue ~ scale(country_gdp) + scale(country_population) + scale(employee_count) + I(scale(employee_count)^2) + (1|country/firmID), data = df)

However, in some versions of this specification I get Error: number of levels of each grouping factor must be < number of observations, but I'm not sure how the total number of levels of a grouping factor are being calculated.  Some FirmIDs are in more than one country, and some are in the same country more than once.
In other versions of the specification I get the error: convergence code 3 from bobyqa: bobyqa -- a trust region step failed to reduce qunable to evaluate scaled gradient Hessian is numerically singular: parameters are not uniquely determinedModel may not have converged with 1 eigenvalue close to zero: 0.0e+00
Re-running the code by assuming country and firm random effects runs without convergence issues, but I don't think it's appropriate to not account for the nested nature of firms and countries:
lmer(log_revenue ~ scale(country_gdp) + scale(country_population) + scale(employee_count) + I(scale(employee_count)^2) + (1|firmID) +(1|country), data = df)

More generally, is this the right way to model the relationship -- or, is it more appropriate to do something like this -
felm(log_revenue ~ scale(country_gdp) + scale(country_population) + scale(employee_count) + I(scale(employee_count)^2) | firmID |  0 | country,  data = df)

Where I add fixed effects for firm, and cluster by country.  Conceptually, what is the difference between these two approaches, as they tend to yield similar results?
As mentioned in the comment below, I'm particularly interested in understanding the intuition behind the difference between the following: (1|firmID) +(1|country), (1|country\firmID) adding fixed effects at both the country and firmID level, and adding fixed effects for firmID and clustering standard errors at the country level.
Comment: Do you have more than one observation per firm??
Comment: A "row" in the dataframe is aggregated at the firm-country level.   But, for a given firmID (e.g. Apple) that firm will exist in multiple countries and therefore have multiple rows attached to that firmID.  Some firmIDs are therefore associated with multiple countries (if it's a multinational company), other firmIDs just have one country (if it's a start-up, for example)
Comment: @BenBolker, thoughts?
Answer: You are trying to fit a hierarchical model to data that are not hierarchical (firms belong to any number of countries, so are not nested in the sense we use the term in multilevel modeling). I would look into cross-classified models.
Comment: Adding fixed effects for both levels will likely lead to collinearity. If you're only concerned about clustering, I'd go with fixed effects for firms and clustered SEs for countries. Multilevel models are very flexible and allow you to do things like estimate the degree to which mean revenue within a particular firm deviates from the overall mean, conditional on the mean revenue in that country. They also yield more valid SEs when you have a higher-level predictor (e.g. country GDP) compared to clustered SEs.
Comment: Is there another term for "cross-classified" models?  That term yields some sparse results, and no R tutorials
Comment: Check this out: http://lme4.r-forge.r-project.org/book/Ch2.pdf
But essentially it's just:
(1| country) + (1|FirmID)
Comment: Thanks so much!  Do you know how this is substantively different from just adding fixed effects for country and firm ID?  Or how that is different from adding fixed effects for firm and clustering standard errors at the country level?


"This is a debugging block" on Permissions page

Question: On my dev site, everything is working fine EXCEPT the permissions pages.  This includes /admin/people/permissions and the permissions pages for individual modules (example: /admin/people/permissions#module-advanced_forum).
I have the Faster Permissions module installed, and this module gives a list of all the modules installed with links directly to their individual permissions. This page is working fine.
All of these pages are working fine in my production site, so there is something about my dev site that is causing this error. Has this happened to anyone before? What could be the problem?

FYI, debugging blocks have been turned off in settings.
Comment: Your screenshot is a dead link and your question is very hard to understand. Please rephrase. What is "Faster Permissions page"?
Answer: If you are using the Omega theme debugging blocks are always visible to uid=1. Check out this issue.
Comment: Thanks Triskelion for your advice, however the login I'm using is user 3586. I am using Omega, however. Considering this issue doesn't happen in my production site, could there be something wrong with my settings in my test site? Could time out settings have anything to do with this?
Answer: I believe I have figured it out. My site seems to have a lot more permissions set than other Drupal sites.  I just doubled the PHP memory limit to 1 GB and the page loaded ALMOST normally. I got an unresponsive script warning. I then looked at the error log for the site and saw that the PHP was timing out, so I doubled the timeout. Now the permissions page loads as it should.


Why isn't my Talos install booting the k8s apiserver, though it otherwise seems functional

Question: I've been trying to get Talos up and running on a few VMs using libvirt. Those VMs appear to be launching etcd and it's clear from the logs the etcd's are talking to each other, and it's also clear that the controller is running in a loop trying to start things, but one of those things does not appear to be the apiserver, and the things it is trying to start are failing because they can't contact the apiserver.
I have verified that I can contact etcd, and pull keys out of it. I can even contact it at the configured vip for the system. I'm using 3 control plane VMs. I tried it with just one as well.
Also, ./talosctl -n <control plane node> ls /etc/kubernetes/manifests reveals that none of the manifests have been put in place.
I'm not sure what information would be relevant.
Answer: You may want to first check the troubleshooting guide and see what works and what does not working properly yet:
https://www.talos.dev/v1.4/advanced/troubleshooting-control-plane/


What's the intuition behind Velicer's minimum average partial (MAP) test?

Question: In my field both the parallel test and Velicer's minimum average partial (MAP) test are commonly used when researchers are considering how many factors to retain in factor analysis or components to retain in PCA.
I find the parallel test reasonably intuitive - we want factors/components that account for more variance than factors/components derived from random data.
As I understand it, in the MAP test we do a PCA/factor analysis with only one factor/component, and then partial that PC/factor out of the correlations between the observed variables, and then we calculate the average squared partial correlation coefficient from the off-diagonals of the partial correlation matrix. Then we repeat the process with two factors/components, and so on. Then we look for the number of factors/components that results in the lowest average squared correlation coefficient.
On some level I think I understand the mechanics of the process described above, but I don't understand how it relates to selecting an appropriate number of factors/principal components. The original paper is short and fairly readable, but I did not feel after reading it that I understood the concept intuitively.
Velicer, W. F. (1976). Determining the number of components from the matrix of partial correlations. Psychometrika, 41(3), 321-327.
Answer: I think the intuition behind MAP can be grasped by looking at the formula of partial correlation, included in Velicer (1976) paper (equation 11), which I also write here for convenience:
$$r_{ij.y} = \frac{r_{ij}-r_{iy}r_{jy}}{((1-r_{iy}^2)(1-r_{jy}^2))^{1/2}}$$
At the numerator you have the partial covariance between each pair of variables $i$ and $j$; this number will go down as you partial out more components, since you are removing systematic variance. You divide this number to get a normalization, pretty much like you divide covariance by the product of the standard deviations in order to have a correlation coefficient that has value between -1 and +1. This denominator contains the two correlation terms between each of the two variables and the component $y$ that you are removing. These correlation terms will go up as you keep removing components, since components will contain more and more individual variability/noise. This makes the denominator as a whole to go down.
So, both the numerator and the denominator go down as you remove more components, the former because partial covariance goes down since you are removing common/systematic variability, the latter because components catch more and more individual variability.
Now, it comes a point at which the denominator starts decreasing faster than the numerator, because you are removing more individual variability than systematic variability in the data. This makes the partial correlation go up. The MAP criterion computes the average of the partial correlations, and tells you to stop when the average partial correlation stops going down and starts going up, i.e. when you are starting the remove more individual variability than common variability in the data.


Genetic limitations to learn certain instruments

Question: This is something that has bothered me for quite a while.
I frequently participate in instrument demonstrations for children. My focus is on wind instruments but I'm also curious about others.
What I noticed is that some children just seem to have a strong affinity to certain instruments. And some seem to be absolutely unable to produce sound on some instruments. I noticed that there are children who just naturally place their lips right on the instrument and others who seem to be physically unable to hold their lips in those positions (think someone who can't roll their tongue but desperately tries to). There are children who blow in a strong and narrow fashion and others who tend to blow much broader, some have a strong grip with their mouth, others a more soft one.
Finger length and lung capacity are also important of course but in children this is hard to factor in since they are not developed enough.
And then there are obvious genetic malformations like missing fingers that of course can severely limit the amount of instruments you can play, but I'm more interested in the not-so-obvious ones.
You see I started thinking that maybe some people just simply don't fit certain instruments and will never do as well on them as others.
So my question is, are there lesser-visible genetic limitations (lip/mouth muscles/lung capacity/blowing capabilities...) that can prevent someone from learning certain instruments? Or can those mostly be compensated by practising?
Comment: If you have severly limited lung capacity (diaphragmatic hernia) that would make wind instruments difficult.
Comment: Josef Hoffman had small hands.  Steinway made him special piano(s).  https://en.wikipedia.org/wiki/Josef_Hofmann#Technique_and_style How many wannabe small hand pianists would get this special treatment from Steinway?
Comment: We had this question recently about lip shape and embouchure: https://music.stackexchange.com/questions/85254/learning-the-flute-embouchure-with-a-teardrop-in-the-lips
Comment: I worked at a band instrument and music store for over 8 years. Anecdotally, I supplement your initial observation: there are some kids that are great at brass instruments and terrible at woodwind instruments and vice versa. As for compensation...I'm certain that there are compensations, but I would recommend...recommending to them that they try a different instrument. They may not want to , but that could change if they realize that they have a "natural aptitude" for another type of instrument.
Comment: Completely independently of music, you are making the unwarranted assumption that, if somebody cannot imitate some movement after being shown, there is some genetic predetermination for it - it has been proven wrong again and again. Nature-vs-nurture is not a useful way to think of people.
Answer: Playing any instrument (save possibly the theremin) requires a physical interface between the instrument and the performer.  If you happen to have an ideal physique for the instrument things will be easier, and if your body is lacking in some way you'll need to adapt.
But having enough desire seems to trump disability.  Not just through practicing, but through a combination of practice and innovation.
I'm a guitarist, and about 15 years ago I took a deep dive into the music of Django Reinhardt.  As part of that I watched every filmed performance of his that I could find, and I had an epiphany: the way guitarists approach the instrument today is at least in part the result of Django's "handicap".
Django was a professional guitarist at the age of 15.  At the age of 18 he was trapped in a fire that severely injured him, and as a result he had two useless fingers on his fretting hand.  Within a half dozen years of the fire he became a renowned jazz guitarist.
Jazz lines make extensive use of arpeggios.  A guitarist with a fully functioning fretting hand might approach an Fm7 arpeggio by playing F and Ab on the 6th string with the 1st and 4th fingers, then C on the 5th string with the third finger, Eb and F on the fourth string with the 1st and 3rd fingers, and so on.  A typical line could go through two octaves and a third, the range of the guitar in a single position.
But since Django had only his 1st and 2nd fingers available, he adapted: F with the first finger, Ab with the 2nd - which shifted to third position.  C was then under his first finger... and Eb on the 5th string put him in 5th position.  He'd slide up to seventh position for the next F, and so on.  Django's arpeggios were diagonal across the fretboard, because that was the only way he could play them.  And the diagonal approach to the instrument meant his range for a typical arpeggio was larger than that of a guitarist without a handicap.  Other guitarists learned to apply this approach to extend their own lines, and "diagonal" fingerings are now something many guitarists study.
So a physical limitation can not only be overcome, but in some instances can change the way other musicians think about the instrument.
You can find other examples of musicians overcoming seemingly impossible hurdles, like the violinist Carl Unthan who was born without arms.  Or one-armed pianist Nicolas McCarthy.  Or Def Leppard's one-armed drummer Rick Allen.
Never say never! :)
Comment: I fully agree. There have been no musicians in my family for generations, and I have been able to pick up a completely new instrument at the age of 25 (I switched over from percussion to saxophone). Most people at my age would say that no new skills can be learnt, but in a matter of years I have personally been able to achieve what most others don't when they start out in a school band and play until the end of high school... Dedication to an instrument is all that it takes. You have to love your instrument of choice and be willing to face it every day.
Comment: @schadjo - I mentioned using a combination of practice and innovation to overcome challenges.  With the problem you describe, you might have been better suited to prior methods - in the early baroque the violin wasn't held under the chin: http://www.baroque-violin.info/vhold1.html
Comment: Perhaps, but this answer does not account for physical pain caused by the design of the instrument in certain hands. I cannot make my palms face straight up without bending my arm and moving my elbow across my body. Growing up, I thought excruciating pain while playing violin was just suffering for my art, but it's more unlucky bone structure. I was never able to find a comfortable way to play the violin. Luckily, I -am- suited to lute family instruments, but I will never be able to play  pieces that require most normal classical techniques.... Perhaps erhu-style would work...
Comment: Very cool. Never realized those were designed for playing that way; I had assumed the artists depicted their subjects holding the instruments that way to make the paintings more dramatic. You learn something new every day.
Comment: Jeff Healey... blind, frets on his lap like a piano.  Undoubtedly successful.
Answer: There are countless examples of people who have substantially overcome major limitations, such as Manami Ito.
This is conjecture, so please take it with a grain of salt, but I find epigenetic effects are far more important than the genetic ones.  There does seem to be a mindset associated with each instrument which yields the best and most expressive playing possible.  Consider the difference in mindset between an oboe player and an electric basist, or a concert percussionist.  While it may be hard to pin the difference down, there is clearly a difference!
If you happen to pick an instrument that matches your mindset, you will find it comes more naturally than other instruments.
There are genetic issues, but they can be overcome.  You mention finger length as one.  One of my piano teachers had a demonstration on this that he loved.  He had me compare the size of my hand to his.  My fingers were substantially longer than his, but he could hit an interval two notes wider than I could.  He had simply taught his hand to relax more than I had, so he could spread his fingers and thumb wider than I could.
Now there are going to be counterexamples.  There's always music designed for the extreme.  If you find music written for someone with Polydactly, you should not be surprised if its hard to play it with just 10 fingers.  However, most music is designed to be played by a wide variety of people, so you'll find genetic limits far and few between.
Now, going back to mindsets, I want to make it clear that this does not mean you must play an instrument that matches your mindset or you will fail.  What it means is that if you pick another instrument, you will have to expand your way of thinking to encompass what the instrument has to teach you.  If you are a lackadaisical person
who isn't too concerned with timing, and you pick up percussion, you will have to learn how to make the instruments make their sound at the right time with nothing but a stick and some willpower.  You will have to figure out how to grow your mindset to make that happen.
I would say the jury is still out as to which is the more important bit of playing music: finding something you play naturally, or finding something that expands your horizons.  I'll leave that bit up to you.
Comment: Do you really mean _epigenetic_? This refers to **inherited/innate** characteristics caused by mechanisms not affecting the sequence of DNA bases (A,C,G,T = adenine, cytosine, guanine, thiamine) in the genes. I believe that it is not clear in what proportions a person's mindset is influenced by (i) their environment, (ii) heredity in the form of the DNA sequences of their genes and (iii) heredity due to epigenetic effects.
Answer: It's impossible to generalize but often genetic weaknesses can be compensated for by learning an instrument. Someone who has naturally weak lungs might strengthen them by learning a wind instrument. Someone who has weak hand muscles can improve them by learning contrabass, although they'll have to work much harder to make progress.
Sometimes there are physical factors that can't be compensated for. Someone who has a teardrop in their lips will have a very hard time getting a good sound on the flute.
But for every genetic limitation you can think of, you can probably find someone, somewhere who has overcome it and turned into an accomplished musician
Answer: The physical question is trivial.  Yes, in the last analysis you have to be able to operate the thing.  Yes, there are inspiring anecdotes of musicians who have managed to overcome seemingly show-stopping physical limitations.  "We (may) have the technology." (Has the prospective player $6M worth of commitment though?) Go, girl!
The more interesting question is why (and if) a certain individual feels drawn towards a certain instrument.  I played piano 'because it was there'.  First year at 'big school' instrumental lessons were offered, I volunteered for trumpet on a whim.  A year later a trombone vacuum arose, I filled it.
I don't actually know anyone who felt born to play a specific instrument, it was more a matter of being thrown the ball, and running with it.  (The great thing about a good education system is that it KEEPS throwing you balls.  You catch some of them.  You can't catch them ALL.)
I'm sure such people exist though.  'Ever since first hearing that sound, I knew I HAD to...'.
'Boys play the heavier instruments.'  Well, OK.  But harpists - the epitome of un-portability - are traditionally female.  Go figure.
Answer: I would say there are no limitations to play an instrument. If you really want to play an instruments, you will be able to learn it one way or the other.
Of course there might be some harder and some easier instruments and some may just be impossible to play for a certain person... but in general, if you put enough effort into it, you'll be able to play an instrument.
Just some examples:

Here is a piano player without any fingers: Piano 1
Here is another one: Piano 2
... and a man with autism: Piano 3

Well, I think you get it. These days you hear every second person say things like "I can't play the piano, because my hands are too small", "I can't play the piano, because I didn't start when I was young"... Don't you think that if a person without any hands can play the piano, that people with small hands should be able to do it as well?
I think many reasons that people name these days are no real limitations. The only limitation that many people got, is that they don't want to put enough effort in learning an instrument ;)
Comment: I suffer from pretty bad carpal tunnel related problems in my hands. As a result I can't form chords (can't move my fingers independently) and fingerpicking gets extremely painful after only a few minutes. Yeah, there are physical impediments to playing instruments. And often they're invisible to the outside observer. Likewise someone with severe asthma probably won't be able to generate the volume of air needed to blow a trumpet or tuba, or indeed produce a stable enough air flow for most any wind instrument.
Comment: Well, like I said, some instruments might be harder than others, you still can play an instrument.

I have cubital tunnel syndrome myself and I have basically the same problem playing the piano. This doesn't mean I'm not able to make music. I'm still arranging music for the piano within sibelius and I'm also able to play flute & harmonica. Even tho there might be limitations for some instruments, that doesn't mean you're not able to play any of them.
Answer: I have been a guitarist for almost 40 years and there is definitely a genetic component to playing an instrument, however, this is not about Darwin but rather about basketball.  I am 5'8 and no matter how much I practiced I would never play in college or the NBA. just as shortness is a genetic trait so are small hands, tongue shape, lip shape etc.  By way of example, I would argue that certain biological factors contribute to your ability to play.  Using myself as an example I have been passionately in love with the guitar for ever. I have practiced almost 4 hours daily and over the years I have discovered several physical and mental deficiencies I have that have thwarted my ability to progress beyond a certain point.  I first discovered how small my fingers were.  I rectified this by having custom built Les Paul necks made.  It sure made a difference. Then I realized how in effective my little finger was.  That sent me off into years of exercises and visits to doctors.  I have experienced a great deal of extra movement but after almost 15 years of working on this I have come to realize that I don't have that certain dexterity that other players have. Next in my effort to play like my hero's eg Gary Moore.  I discovered that I don't have fast muscle twitch.  So no matter how much I practice I have achieved all the speed there is for me to obtain.  Now to the mind portion, although I am fairly accomplished, I don't have the mental capacity to see scales, notes etc.  I believe that certain people have an innate ability to see and remember patterns on the fret board, scales arpegeos etc.  I can't.  All of these factors have come from my genetic heritage, however this is not Darwin only music.


Redis and Internal Page Cache?

Question: I just set up Redis on a site that has been having some performance problems, and it seems to be running well so far. Does anybody know if it would be recommended to also run the Internal Page Cache and/or Internal Dynamic Page Cache module(s) in addition to Redis, or is this redundant? There isn't much documentation around yet regarding Redis and D8.
Comment: Redis is a cache storage backend. It makes caching faster, but doesn't change the way drupal caches data.
Comment: So then the answer would be that enabling those module is not redundant?
Comment: Only if speed is so much improved that you can do without one of those caches.
Answer: The Drupal modules decide what to cache (and for how long etc), Redis is just where the cached data is stored.
Having both/all enabled is not inherently redundant (though as 4k4 noted in the comments, there's a theoretical chance that one cache will improve speed so much that it renders the other redundant in terms of further speed improvements).
Enabling the lot will probably be common practice, and if not with Redis as the storage backend then Memcache, etc.
Answer: As said before Redis is just a "bin" where to store cache, it should be faster than the database bin (default Drupal cache bin).

Dynamic Page Cache module should always be enabled or you get crappy performances.
Internal Page Cache module could be disabled if you have already a cache server in front of your Drupal (for example, Varnish), this module cache whole pages for anonymous users only.

These two modules are enable by default on Drupal 8; it is safe to enable them.

Redis and Internal Page Cache?


JavaFX HTMLEditor - focus webView (TextArea)

Question: I have created a chat using the JavaFX HTMLEditor Component, after sending a message the Editor isn't focused anymore since you press the send button which is focused for the moment). I'd like to somehow focus the editor, I have already Googled but didn't find an answer.
Answer: <code>  void editorWebViewRequestFocus()
  {
    final WebView view = (WebView) ((GridPane) ((HTMLEditorSkin) editor.getSkin()).getChildren().get( 0 )).getChildren().get( 2 );

    Platform.runLater( () ->
    {
      view.fireEvent( new MouseEvent( MouseEvent.MOUSE_PRESSED, 100, 100, 200, 200, MouseButton.PRIMARY, 1, false, false, false, false,
          false, false, false, false, false, false, null ) );
      editor.requestFocus();
      view.fireEvent( new MouseEvent( MouseEvent.MOUSE_RELEASED, 100, 100, 200, 200, MouseButton.PRIMARY, 1, false, false, false, false,
          false, false, false, false, false, false, null ) );
    } );
  }
</code>
Answer: Try this
<code>  WebView webView = (WebView) htmlEditor.lookup("WebView");
    ((HTMLBodyElementImpl) ((NodeListImpl) webView.getEngine().getDocument().getElementsByTagName("body")).item(0)).focus();
</code>
In addition to focus, you can set and get text and much more


How to prevent duplicate http requests?

Question: We have Intermec CK71 mobile devices (WiFi). There will always be a scenario in which the device sends a request (GET, PUT, or POST), then loses connection. What methods can we use to prevent duplicate PUTs or POSTs? How does the client device know whether or not the server processed its request before losing the connection?
I have seen similar posts like this but the marked answer doesn't go into much detail. I'm not even sure where to begin. Should I be looking into caching (ETag, last modified), or some type of handshaking?
The client device has the .Net Compact Framework 3.5 on it and is hitting the server via its Web API 2 endpoints.
If someone can point me to the right direction or offer any suggestions it would be much appreciated. Thanks.
Answer: I am not using REST but as far as I read the information there is no easy way to get an acknowledge and avoid duplicate POST.
As with other high level API frameworks you are tied to what the API offers and it looks like the designers did not think about connection aborts.
The easiest way to workaround this seems to use an unique ID with every post and check the server for knowing these UID before re-posting. If the server does not response with OK for an POST, you have to assume the connection has broken or other things went wrong. Then query the server for the UID you posted to know if the pervious POST was succesful before you try another POST with the same data and UID.
Possibly there is some transaction encapsulation available with REST as available for sql server. A 'transaction' protocol would ensure that a POST has been processed succesfully or will be 'rolled' back, if something failed.
Sorry, but I do not know much about REST.
Comment: Yep, pretty much dependent on the server API to provide an means of either asking it if something was applied (so doing a GET, and if you get a 404 Not Found then do the POST), or having the API detect the duplicate based on a unique ID and returning an error to tell the client "I already have that".

How to prevent duplicate http requests?


Why do quartal progressions typically not utilize common tones?

Question: Typically chord are built in thirds, but in quartal harmony chords are built in fourths instead. One pattern in quartal harmony I noticed was chords tend to move completely in parallel even if common tones exits between notes as demonstrated in this Debussy passage:

And this Jazz guitar passage:

In standard harmony one would want to utilize common tones between chords, but it seems even when there are common tones between chords, parallel motion is instead preferred. What is the reasoning behind this complete parallel motion between chords?
Comment: Interesting question, but I'm not sure this tendency really exists, even though I don't have counterexamples. Anyway, your second example really does not corroborate your thesis because it's just an ordered collection of all fourth voicings in the scale. You might as well have shown all standard chords (in thirds) in a major scale in increasing order (C, Dm, ...) and argue that this 'progression' doesn't use common tones.
Comment: @PatMuchmore There's nothing to worry about Pat. I like hearing your answers and personally I would like the site to be filled with more questions about topics like this. I tend to gather questions about passing thoughts I had while studying passages and techniques and tend to post a few in very short periods when I do.
Comment: I swear I'm not stalking you Dom. I only just noticed you were the question asker. I think we just have similar interests. Also, you tend to ask more challenging and/or obscure questions that don't already have a million answers before I happen to check on the site. Anyway, sorry.
Answer: I think there are some assumptions in your question that are false.
First: Quartal harmony emerges and starts getting used extensively in Western music in the late-19th-, early-20th century. At the same time, many composers were also exploring different ideas about how chords can connect, including chord planing, which involves holding the same chord structures and simply moving them up and down in parallel as opposed to the more traditional voice leading that would avoid parallel 5ths and 8ves and that would tend to use common tones. Debussy, the composer of your first example, uses chord planing techniques in a huge chunk of his music, regardless of whether he's using triadic or quartal harmony. I think the phenomenon you're pointing to is more likely just a confluence of two different aspects of chord usage around the turn of the 20th-century.
Second: Although I see why you are pointing to The Sunken Cathedral as an example of quartal harmony, it actually isn't a very quartal passage. The first measure is chord planing of harmonies that involve m3s and P4s above a root. This is just as close to being a triadic harmony (minor seventh with missing third) as it is to a quartal one (D-G-[missing C]-F. The second measure only has two unique pitches in every chord, just parallel 4th intervals with octave doubling, and doesn't really qualify as a full blown quartal harmony, which would really need at least one more fourth added to the stack.
Third: If we're being fairly loose about what constitutes a quartal or triadic harmony (that is, allowing skipped notes in the stacking) then the harmonies are actually relatively hard to distinguish from one another. The more triadic extensions you have, especially with any skipped notes, the closer your harmony becomes to being conceivable as a fourth or fifth stacking. As an extreme example, a C9 chord without third or seventh (C-G-D) is identical to a fourth or fifth stack, and a diatonic C13 chord with all notes (C-E-G-B-D-F-A) is indistinguishable from a quartal harmony except in voicing (B-E-A-D-G-C-F).
These caveats being made, I think it is possible that common tones would be less bountiful in a quartal universe because, unlike thirds which can be major or minor without utterly changing their function or overall sonic quality, fourths and fifths have to be one quality, perfect, lest they sound like a completely different interval. Changing from a M3 to a m3 or vice-versa is just a shift between two different consonant qualities. Changing from a P4 to +4 or P5 to °5 is a shift between an extremely stable consonance to an extremely unstable dissonance. Moving in the opposite direction by one half step—P4 to °4 or P5 to +5—is a shift into chords that just sound like enharmonically misspelled 3rds and 6ths. As such, there are somewhat fewer harmonies available involving the same tone, especially new harmonies that will involve smooth motion in the non-common-tone voices. [Your guitar example does involve the occasional tritone, but I don't think that's very idiomatic to a quartal harmonic universe.]
If I try to imagine an alternate universe in which Western harmony never gravitated toward thirds as a consonance (perhaps a universe in which Ptolemaic tuning was never pursued, and composers had stuck with a purely Pythagorean tuning), then I picture a world in which voice-leading as we know it would not exist in any sort of recognizable way at all. With only a few exceptions, I think composers would be choosing between smooth, conjunct writing without common tones and rough, disjunct writing with common tones. It's an interesting thought experiment, but I think that the grammar of common-practice tonality only evolved because of the triadic vocabulary already being pursued, different vocabularies would have developed different grammars.
Comment: Great thoughts here. I think it's also important not to equate Parallelism with Quartal vocabulary. Pat's third paragraph addresses the ideas of shifts in harmonic language where instead of linear function, we travel amidst pitch-regions. Debussy was a fan of obscuring - both harmonic function and form. As Pat points out, extensive upper-tertian use saturates the harmonic aural pallet and renders "functional" harmonies as inert. The result is a more smooshy, cloud-like mass that temporally rolls along.
Comment: The chords in the Debussy extract have no 3rds. The idea of 3rds came from an earlier version of this question, which contained an erroneous quotation of the passage. The correct music is an even better example than the earlier version was, of the quartal harmony referenced in the OP.
Answer: I'm not sure that parallel motion is invariable - I think back to a lot of middle period Bartók (although he almost invariably spices the harmony with augmented fourths) - but I think in situations such as the examples you have given here, the colour, the sonority of fourths is a consideration. These are essentially melodic gestures that are coloured by the consistent use of stacked fourths. Consider what happens when you hold over the common notes: you end up with inversions, and other intervals that are latent in the stacked fourths start coming to the fore, so you start losing that distinctive sonority.
Here's more or less what I mean:

Before the double bar line is a pretty straightforward progression of parallel fourths not unlike your guitar example. After the double bar line is the same progression holding common tones. Note the pitches within the brackets at (a) and (b). (a) is embedding a 2nd inversion E Major chord; (b) is embedding a first inversion A minor chord. Those are definitely going to have an effect on the sonority.
Note too that the suggestions of functional harmony are even somewhat different. In the first example, all the voices are outlining a melodic half-cadence. In the second example, leading tone movement between the end of the first bar and the beginning of the second create a similar suggestion of dominant to tonic movement, but that suggestion is strongly reinforced by the embedded triads, and the F-B drop in the top voice does little to dispel that - the impression is closer to a quasi-authentic cadence.
This is a contrived example, but it illustrates that, when you are trying to set up a desired harmonic allusion by purely melodic means with colouration provided by a set vertical sonority, holding the common tones might disrupt the colouration and add a set of (more functional) harmonic implications that might differ from what the melody implies. None of that is necessarily a bad thing, but I don't think it was what your examples were aiming for.
Answer: I would make one distinction here in particular.  Though not necessarily always the case, often times chords such as this are not so much quartal chords as they are quartal voicings.  This is a good bit more obvious in the Jazz example.  The example you provided also shows the chord symbols above, which are all indeed traditional triad based chords within the Jazz idiom.  If you were to hang onto common tones between chords, it would completely subvert the quartal voicings. Miles Davis did a wonderful job with Kind Of Blue in utilizing a quartal voicing for triad based chords.  I like this example because it really spells out the concept of available tensions, ie, within Dorian, all tensions (9/11/13) are considered available and by stacking the fourths all the way up, you can hit each of them.  Although, if I remember correctly, he threw a third on the top of those chord voicings.  I believe this would be to prevent the b9 dissonance that would occur between the 9 and 3 of the chord, or the 13 and 7, as well as the ability to move the voicing around as he does.
As others have mentioned, this can also happen with chords that would fall more in the category of quartal chords but by a slightly different means.  Essentially hanging onto the common tones can spell out other triadic relationships in such a way that it could subvert the quartal intention.   I would not consider myself well versed enough to dive into planing as Patrx2 did and would find it unnecessary with the explanation he gave being quite good.
Answer: While not present in these examples, the inversions of the quartal triad (a stack of three perfect fourths) often go unnoticed and are, in fact, essential to utilizing common tones in quartal harmony.
Consider the chord (from lowest to highest) A-D-G. If we consider this to be the root position of the quartal triad, then its first inversion is D-G-A (known colloquially as a sus4 chord), and its second inversion is G-A-D (known colloquially as a sus2 chord).
Why is this important? Well, consider how we use common tones in traditional tonal chord progressions:
Take a V-I cadence of G resolving to C. We would typically resolve G-B-D by keeping G where it is and then resolving the other voices upwards to spell G-C-E. We don't see it often because of the old prohibitions against parallel fifths, but in a free harmonic context we could simply move G-B-D up a fourth to C-E-G. This is the type of planing we see above; if common tones are available when moving from one quartal chord to another, then the ONLY way to hold the common tone over is to invert one chord, the other, or both (The only exception being if you move up or down by one or more fourths, such as A-D-G moving up to D-G-C).
Consider this jazz piano example:
<code>  One voicing of an Am7 with an added 11th would be A-G-C-D. Note that this is an inverted quartal
  stack (A-D-G-C). If we wanted to resolve to Dm7 (with another added 11th), we could plane up to
  D-C-F-G (again, an inversion of the quartal stack D-G-C-F), but it would be a more comfortable
  and idiomatic to voice the chord as D-F-G-C, keeping the G as a common tone.
</code>
This is all done by way of inverting quartal stacks. In the case of the guitar chords, they are planed in this manner because, as was the case with the piano example, it is more comfortable and idiomatic to play the chord progression as a series of quartal stacks. Since guitar strings are (mostly) tuned in fourths, playing two different stacks of fourths is as simple as moving up or down a fret. On the piano, large stretches of a tenth or more typically necessitate a rearrangement of the quartal chord in order to comfortably play the chord.
As for Debussy, planing is a hallmark of his style. More over, he was evoking a style of medieval music known as organum. Organum consisted of a single perfect fifth/fourth doubled over several octaves, and most textbook examples of the style are nearly identical to the chords and voicings Debussy used in measure three.
Lastly, planing of this sort is not limited to 20th century quartal chords; see the opening measures of Beethoven's Piano Sonata No. 3, mvt. 4 for an example of diatonic planing by similar motion :)
-As a side note, it is worth noting that extended minor seventh chords and major seventh chords get some of their cadential stability because they are inverted quartal stacks:
<code>  -Am7 add 9, 11, +13 = A-C-E-G-B-D-F# rearranges to: F#-B-E-A-D-G-C
  -CM7 add 9, +11, 13 = C-E-G-B-D-F#-A rearranges to: F#-B-E-A-D-G-C
</code>


Erro ao instalar npm install @react-navigation/stack -> expo start disconnected

Question: sou novo no React native e estou tentando instalar o react navigation stack através do comando npm install @react-navigation/stack para utilizar em um projeto de um app com o react native, no entanto após executar esse comando para instalar essa biblioteca, dá erro como se o expo cli fosse desinstalado por esse comando, algum arquivo excluido não sei ;(
Preciso instalar essa biblioteca para criar o aplicativo. Como proceder nesse caso?
Veja o que ocorre no cmd ao executar o comando npm install @react-navigation/stack

Depois que rodo esse comando, o expo dá erro :(

Preciso muito da ajuda de vocês! ;)
Answer: Ao inciar o servidor do expo através do yarn start da esse erro no cmd
Answer: Tá falando que o RN não esta instalado, tente instalar de novo. Se você instalou e ainda ficar esse erro, tenta criar o arquivo em outra pasta
Answer: Consegui resolver dessa forma, rodando os comandos:
Npm upgrade
Npm i
Npm i (nome-do-pacote) -> no meu exemplo é o npm install @react-navigation/stack


Creating an applet to get an image

Question: Is there anything wrong with doing this:
<code>public static Image getPicture01()
{
    Applet app = new Applet();
    Image t = app.getImage(app.getClass().getResource("/res/pic01.png"));
    return t;
}
</code>
My goal is to get a resource (image) from my project in Java, and use it.
Answer:
Is there anything wrong with doing this:...

Yes, it is totally unnecessary, wasteful (creating an unneeded object, Applet), and there are better alternatives -- ImageIO.read(...) for one.

Creating an applet to get an image


TypeError: res.blob is not a function

Question: I want to implement file download using this Angular 6 code:
Rest API:
private static final Logger LOG = LoggerFactory.getLogger(DownloadsController.class);

@GetMapping(path="export")
public ResponseEntity<byte[]> export() throws IOException {
    File pdfFile = Paths.get(EXTERNAL_FILE_PATH).toFile();

    byte[] fileContent = Files.readAllBytes(pdfFile.toPath());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    return response;
}

Service:
import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";
import {Observable} from "rxjs/index";
import {environment} from "../../../environments/environment";
import {HttpUtils} from "../common/http-utils";
import { map } from 'rxjs/operators';
import {Http, ResponseContentType} from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class DownloadService {

  constructor(private http: HttpClient) {
  }

  downloadPDF(): any {
    return this.http.get(environment.api.urls.downloads.getPdf, {
        responseType: 'blob'
      })
      .pipe(
        map((res: any) => {
          return new Blob([res.blob()], {
            type: 'application/pdf'
          })
        })
      );
    }
}

Component:
import {Component, OnInit} from '@angular/core';
import {DownloadService} from "../service/download.service";
import {ActivatedRoute, Router} from "@angular/router";
import {flatMap} from "rxjs/internal/operators";
import {of} from "rxjs/index";
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-download',
  templateUrl: './download.component.html',
  styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {

  constructor(private downloadService: DownloadService,
              private router: Router,
              private route: ActivatedRoute) {
  }

  ngOnInit() {
  }

  export() {
    this.downloadService.downloadPDF().subscribe(res => {
      const fileURL = URL.createObjectURL(res);
      window.open(fileURL, '_blank');
    });
  }
}

The file is present in the directory but when I try to download it I get error:
ERROR TypeError: res.blob is not a function
    at MapSubscriber.project (download.service.ts:24)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:84)
    at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:15)
    at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)

Do you know how I can fix this issue?
Do I need to add additional configuration in order to download the file via Angular web UI?
I use spring-boot-starter-parent version 2.1.0.RELEASE and angular 6
Update: I tested this but nothing happens:
downloadPDF(): any {
    return this.http.get(environment.api.urls.downloads.getPdf, {
        responseType: 'blob'
      })
      .pipe(
        map((res: any) => {
          return new Blob([res], {
            type: 'application/pdf'
          })
        })
      );
    }

Comment: You don't need to call `.blob()` on it if you pass the responseType like you have. It should already be a blob
Comment: @user184994 I updated the code but nothing happens when I press the button. Any idea where I'm wrong?
Comment: Is your browser trying to block the popup or anything? Add a few `console.log` in the code to find out how far its getting
Comment: Ok, it turns out that blocker is causing the problem. Is there some way to avoid it?
Comment: Ok, this line is the problem: `return new Blob([res.blob()], {
            type: 'application/pdf'
          })` Should I use new Blob?
Comment:
Comment: Please refer these links. * https://stackoverflow.com/questions/37046133/pdf-blob-is-not-showing-content-angular-2
* https://stackoverflow.com/questions/50018730/http-failure-during-parsing-for-http-while-downloading-pdf-file
Answer: Use the res.body instead of res while constructing the Blob.
downloadPDF(): any {
    return this.http.get(environment.api.urls.downloads.getPdf, {
        responseType: 'blob'
      })
      .pipe(
        map((res: any) => {
          return new Blob([res.body], {
            type: 'application/pdf'
          })
        })
      );
    }

Comment: It's correct. I suppose that something is missing into the typescript code?
Comment: Any other ideas?
Comment: try once with `res._body` instead of `res.body`

TypeError: res.blob is not a function


Understanding 'strictness' in regex grammar

Question: In writing a grammar/parser for a regex, I'm wondering why the following constructions are both syntactically and semantically valid in the regex syntax (at least as far as I can understand it)?

Repetitions of a character class, such as:

Repetitions of a zero-width assertion, such as:

Assertions at a bogus position, such as:

To me, this sort of seems like having a syntax that would allow having a construction like SELECT SELECT SELECT SELECT SELECT col FROM tbl. In other words, why isn't the regex syntax defined as more strict than it is in practice?
Answer: To start with, that's not a very good analogy. Your statement with multiple SELECT keywords is not, as far as I know, part of the SQL grammar, so it's simply ungrammatical. Repeated elements in a character class are more like the SQL construct:
SELECT * FROM table WHERE Value IN (1, 2, 3, 2, 3, 2, 3)

I think most (if not all) SQL processors would allow that. You could argue that it would be nice if a warning message were issued, but the usual SQL interface (where a query is sent from client to server and a result returned) does not leave space for a warning.
It's certainly the case that repeated characters in a character class are often an indication that the regular expression was written by a novice with only a fuzzy idea of what a character class is. If you hang out in SO's flex-lexer long enough, you'll see how often students write regular expressions like [a-z|A-Z|0-9], or even [begin|end]. If flex detected duplicate characters in character classes, those mistakes would receive warnings, which might or might not be useful to the student coder. (Reading and understanding warning messages is not, apparently, an innate skill.) But it needs to be asked, Who is the target audience for a tool like Flex, and I think the answer is not "impatient beginners who won't read documentation". Certainly, a non-novice programmer might also make that kind of mistake, usually as a result of a typo, but it's not common and it will probably easily be detected during debugging.
If you've already started to work on a parser for regular expressions, you should already know why these rules are not usually a feature of regular expression libraries. Every rule you place on a syntax must be:

precisely defined,
documented,
implemented,
acted upon appropriately (which may mean complicating the interface in order to allow for warnings).
and all of that needs to be thoroughly tested.

That's a lot of work to prevent something which is not even technically an error. And catching those errors (if they are errors) will probably make the "grammar" for the regular expressions context-sensitive. (In other words, you can't write a context-free grammar which forbids duplication inside a character class.)
Moreover, practically all of those expressions might show up in the wild, typically in the case that the regular expression was programmatically generated. For example, suppose you have a set of words, and you want to write a regular expression which will match any sequence of characters not in any of the words. The simple solution is [^firstsecondthirdwordandtherest]+. Of course, you could have gone to the trouble of deduping the individual letters in the words, -- a simple task in some programming languages, but more complicated in others -- but should it be necessary?
With respect to your other two examples, with repeated and non-terminal $, there are actual regex libraries in which those interpreted in some different way. Many older regex libraries (including (f)lex) only treat $ as a zero-length end-of-string assertion if it appears at the very end of the regex; such libraries would treat all of those $s other than the last one in a$$$$$$$$ as matching a literal $. Others treat $ as an end-of-line assertion, rather than an end-of-string assertion. But I don't know of any which treat those as errors.
There's a pretty good argument that a didactic tool, such as regex101, might usefully issue warnings for doubtful regular expressions, a task usually called "linting". But for a production regex library, there is little to be gained, and a lot of pain.
Comment: oh wow, what a beautiful explanation -- thanks so much for putting in the time. I think the most important part I took away from it is: `In other words, you can't write a context-free grammar which forbids duplication inside a character class`.


How can I add a "Back to Search" link to user profiles?

Question: I have a view with exposed filters that allows users to search for other users on my site.  The view displays users' profile pictures, and clicking a profile picture takes one to the relevant user's profile (put together using Panels).
I'd like to display a "Back to search results" link on the user profile whenever someone clicks on the link (picture) in the view and visits the profile.  How might I go about doing this?
I'm using D7 with Panels and Views 3.
Comment: How did you solve hard-coded the view URI?
Answer: You can do this wih a new module modifying the user profile view.
// Implements hook_user_view().
function MY_MODULE_user_view($account, $view_mode, $langcode) {
  $account->content['link'] = array(
    '#weight' => -10,
    0 => array(
      '#markup' => 'Back to Search',
    ),
  );
}

Note: When adding a hook always remember to clear caches
If you also want to preserve the filter that the user has applied you can do so within your filter in the view by selecting 'remember the last selection' and selecting the roles that you want this for.
Comment: Thanks, but I wasn't able to get this to work.  As I said in the question, I am overriding the user profile display in Panels, so perhaps the problem is Panels overriding the code in the custom module?
Comment: Also, I can't hard-code the view URI; there are different ways to search so I need to link back to the view that the searching user was using.
Comment: There is an option in views to preserve the filter (as mentioned above) so that should help with your second point. I havent used panels in a while and haven't used them much tbh views tends to do all I need. But if you can add a hard coded link to your user profile panels display and select that option on the filter in the 'search user' view then it should all work great.
Comment: If the preserve filters really wont cut it then you could use a jquery back button as explained here http://www.jquery4u.com/snippets/jquery-button-go-previous-page/
Comment: This answer doesn't solve problem with "hard-coded the view URI"


what if eigenvector of 2x2 matrix after plug eigenvalue in matrix and only one parameter left?

Question: I stuck this problem
$\begin{bmatrix}
1 & 2 \\
0 & 1
\end{bmatrix}$
the eigenvalue is 1
when try to find the  eigen vector I found
$\begin{bmatrix}
1-1 & 2 \\
0 & 1-1
\end{bmatrix}$
$\begin{bmatrix}
0 & 2 \\
0 & 0
\end{bmatrix}$
or $2x_{2}=0$
or $ x_{2}=0$
the eigenvector might be in this form
x
0
(I try to write eigenvector by Latex by always get error -*-)
what is the vaule for $x$? because no $x$ left after I plug in eigenvalue in matrix
Answer: For every $x\in\mathbb R\setminus\{0\}$, the vector
$$\begin{bmatrix}x\\0\end{bmatrix}$$
is an eigenvector of the matrix
$$\begin{bmatrix}1&2\\0&1\end{bmatrix}$$
Comment: thank you for help ^ ^
Answer: If $\vec v$ is an eigenvector corresponding to an eigenvalue $\lambda$, then so is any other non-zero scalar multiply of $\vec v$. So for any $x \ne 0$,$$\begin{bmatrix}x\\0\end{bmatrix}$$
is an eigenvector with eigenvalue $1$ of this matrix. If you only need one, you usually pick an easy one such as:
$$\begin{bmatrix}1\\0\end{bmatrix}$$
Comment: thank you for help ^ ^


How should this half-diminished seventh chord from "Christmas Time Is Here" be analyzed in terms of its harmonic function?

Question:
Hi everyone.
I'm working on an analysis of Christmas Time Is Here, which is in F major.
I'm trying to determine the best way to analyze the Bm7(♭5) chord circled in the image. I have 3 explanations right now:

It is a viiø/V resolving (after moving through the B♭m7 passing chord) to iii7, which is the relative minor substitute for V.
It is a ♯ivø7 chord borrowed from F-Lydian.
It is a iiø7/iii or a ivadd6/iii, tonicizing A minor.

Do any of these seem to be the best way to go about analyzing the chord? Is there a better way of analyzing it that I haven't included? I'd love to read some thoughts on how to explain the function of this chord in the music. Thanks in advance, and happy holidays!
Comment: In conjunction with Richard's answer I would be most inclined towards your 3., that is, it is introducing a move to A minor whilst also generating this downward parallel movement back to the cadence
Comment: You asked this same question a year ago, and the same two people responded: https://music.stackexchange.com/questions/92632/how-would-these-chords-from-christmas-time-is-here-be-analyzed?rq=1
Comment: @Peter I knew this question seemed familiar, but I never would have dreamed it would have been such an exact duplicate. Thanks for pointing this out!
Comment: Yeah, I only asked again to see if there were any different interpretations that I didn't read when I asked it last year, and I wanted to see if people agreed with any of my analyses of the chord. I can close the original.
Answer: I see and jazz musicians use the #IVm7b5 (Bm7b5) mostly in one of two ways:

It can be a non-diatonic substitution/reharmonizaion for the diatonic IVmaj7 (Bbmaj7) chord or iim9 (Gm9) chord. It has 3 notes in common with each of these two chords, D F and A giving it a somewhat subdominant quality despite the tritone it contains. For example, the last 8 bars of the song "Emily" starts on a iim7 but many jazz players use this #4 chord as a substitution in that tune.

It is also commonly used as the beginning of a cycle of fifths descending progression which ultimately leads to the tonic: B-E-A-D-G-C-F. These chords can be 2-5's or all dominants or any combination of the two. Any of these chords can be replaced with a tritone substitution which would make for a chromatic descending progression, which is mostly the case here. The Bm7b5 functions like the 2 of a 2-5 to the iii chord in these cases even though in this song there is a chromatic m7 chord instead of a dominant going to the Am7.

In the case of this song, it actually is a bit of both. You can replace the Bm7b5 with either a Gm9 or a Bbmaj7 and the harmonic flow would not change all that much. It also uses a combination of cycle of 5ths and descending chromatic chords to go from B to F.
Some other examples of this usage are the second 8 bars of "Night and Day" and the second 8 bars of "All God's Children Got Rhythm".
Comment: So are you saying that "Dm6/B" interpretation is plausible only if it's used in a circle-of-fifths motion like a series of 2-5's? I think the Bm7-5 chord can be replaced even with a plain regular Dm in this song and it will pretty much the same thing. Just slightly less special flavor and the bass motion to Bbm gets bigger.
Comment: @piiperiReinstateMonica Whoa, where did I say that? I gave two different examples of how the chord is "mostly" used. There are many other less common way it can be used, for example, leading to a tonic chord in second inversion (Bm7b5-F/C) or even as an ambiguous tonic chord as in the first chord of "Inner Urge" by Joe Henderson. The Dm you mentioned would work, in the 5th bar of "Polka Dots and Moonbeams" in the key of F, either a Dm or a Bm7b5 are played by jazz musicians and is one of those spots you listen out for when faking the tune with guys you have never played with.
Comment: @piiperiReinstateMonica I see you prefer the spelling of Dm6/B as do many others. I know the history of how Dizzy and Monk used to call it that. However I prefer the m7b5 label for 2 reasons. First, almost every time Dizzy or Monk used that chord it was as part of a 2-5 in minor (A Night in Tunisia, Round Midnight) so the m7b5 spelling makes more sense as a 2-5. Secondly, is it's a root position 7th chord. Whenever possible I like to spell a chord from the root as opposed to as an inversion because it makes it easier to see the function, especially when reading, playing and improvising.
Comment: I was just reading your description and trying to see which of the two categories would fit the "modified vi" interpretation, which to me feels the most natural one just by playing and listening. I'm a bit reluctant to use the "m7-5" notation, because when used in pop lead sheets for non-jazz players it tends to be played as a regular m7, which often breaks the harmony progression and clashes with the melody. And because that's how I first learned to know the chord as a kid - as a m6 but with the six in the bass, giving the added bonus of a fourths/fifths bass movement in a 2-5 sort of way.
Comment: @piiperiReinstateMonica I am a BIG fan of m6 chords but more in first inversion and mostly as a i or a iv chord. It just doesn't sound like a m6 chord to me once you move the 6th to the bass. Maybe it's because I'm primarily a bass player and play and analyze everything from the bottom up. Hearing and analyzing it as a vi is legitimate and justifiable, things can be interpreted in different ways. As for your reluctance to use it in notation, a musician that knows chord symbols should know that chord and not playing the b5 is simply a mistake, like playing a C7 instead of a Cmaj7.
Comment: I really enjoyed seeing this answer, and it makes so much sense to me now. Thank you for clearly indicating ways that the chord can be used. The descending cycle of fifths progression is very cool, and it's wonderful how it is disguised in this music. Thanks for the answer!
Answer: I would argue that it's the beginning of a larger pattern of chromatically descending seventh chords. Notice that this Bø7 moves to a B♭m7, and this B♭m7 then moves through m7 chords built on A, A♭, and finally G, this last chord being the ii7 of the tonic F.
We call this—when a chord shape is moved up or down in tonal space—planing. And although the planing isn't exact beginning with this Bø7 (if it were exact, it would have an F♯ to make it a m7 chord like the successive harmonies), I think it's significant that the "wrong" pitch, F, is the tonic of the entire excerpt.
Ultimately, I'm not sure it's helpful to give a Roman numeral to this chord, Instead, I think it's best to view this Bø7 as beginning a prolonged sequential move to the ii7 that sets up the cadence on the Fmaj9.
Comment: Thanks very much for this answer. I agree that analyzing this as a planing progression might be the best option. Maybe mixed planing since it isn't completely diatonic planing nor real planing. Very interesting how smooth it sounds. I need to explore jazz harmony more!
Answer: It starts off a 'cycle of 5ths' sequence leading to the tonic with half the chords being ♭5 substitutions.   Without substitutions the roots would be B, E, A, D, G, C, F.     A very common harmonic cliche, with or without the substitutions.
Comment: This definitely makes sense, thanks for this answer!
Answer: I see the Bm7-5 chord as a variation of Dm or Dm6. If you want Roman numerals, it would be something like vi6/IV#. Try playing this expanded three-step sequence in place of the Bm7-5: Dm - Dm/C - Dm/B. But the song skips straight into Dm/B which is really the same thing as Bm7-5. And then it goes to Bbm.
Sometimes that chord is used towards the end of a longer progression, and then you could do for example ... Bm7-5 (=Dm6/B) - F/C - C7 - F. Or something like Bm7-5 - C7/Bb - F/A - Abdim - Gm7 - F.
Edit. If we should look at all possible uses of the chord, not only this song, then how to see a Bm7-5 depends on where you're coming from, or maybe where you're trying to move the harmony with it. A chord is a sum of its parts, and all interpretations are possible at the same time. If there's a B note, it allows for a half-step motion to Bb or C, or a fifths motion to E.
If we're in the key of F (expecting to eventually get home to F), and the previous chord is Gm9, then Bm7-5 is better seen as G9/B - a bass movement of a third, and a temporary modal mixing of D Dorian into the picture.
Comment: I agree with a lot of this, especially the reference to temporary modal mixing of D Dorian (F Lydian). Thanks for the answer!


How do you add validation (constraints?) on a paragraph? Compare two fields

Question: How does one go about adding validation (contraints?) on a paragraph?
I need to compare two entity reference fields on submission. If one field has a certain entity referenced, the other cannot have certain entity references.
I'd be interested in restricting the autocomplete options as well, but that simply won't be enough as I need to ensure that they user doesn't manually enter another entity value.
Comment: And it does not help to validate with `$form['#validate'][] = 'my_custom_function'` and limit the entities with a `hook_form_alter`
instead of using contraints in this case??
Answer: You simply inherit from the the default EntityReferenceWidget and you will call it like MyParagraphEntityReference widget. You can here both change the way how the autocomplation works and also how you validate the entered data.
This is page may help you.


usb debug authorixation not shown (how to push files onto unauthorized adb device(rooted device) (4.4.2))

Question: i have a lava iris atom 2 which was in kitkat 4.4.2
i installed xposed -- (gravitybox, eggster, monsterui)
i was satisfied with my new lolipopish look
but only thing annoying was the settings it had the light theme
and all the icons were white so they were invisible
then i used apk-editor to change icons
actually i used only wifi icon to be changed then i compiled it with the same apk-editor
then replaced it with root browser,
guess what the settings was in accesible
i thought restarting might fix the problem
then i had the two errors constantly poping up
Unfortunately, the process
com.android.systemui has
stopped
AND
Unfortunately, the process
com.android.phone has
stopped
i cant even use my phone for a sec
i have a pattern lock which takes 3 sec to complete
total time i can access the phone 5 to 10 sec
i quickkly completed the pattern and the launcher responded
then i couldnt find settings
in status bar it was the same no settings
i am hardly able to open status bar and launcher
i tried flashing stock rom
no progress its blank(device not detected i guess)
all drivers are present, i tried adb (waiting for device in fastboot mode) (i guess because it is unauthoritised)
i have backed up settings.apk in case of a bad thing but i cant push it either.
i didnt get a prompt to allow adb
my recovery is dead too
i tried cwm ported for my device and its dead
i didnt have the backup
what should i do??
can i push it / bypass prompt
i get only some sec to wait for allowing it
i tried sending requests non stop through cmd
i get some sound (notification ) but no prompt
help me guys.
i really need it
Answer: If your device didn't connect to your system then, you need to follow the step and install the driver.
Step 1: Download and extract the zip file on your computer then connect your android smartphone via Lava USB cable to your personal computer or laptop.
Step 2: Click on the Start button or you can also press WIN key to directly active start menu then either you have to right click on the "Computer" option or you can also press Shift+F10 key to open the cascading menu and choose "Manage" option. Click on the "Device Manager" option in the Computer Management dialog box. Now you can see your mobile name or number with yellow triangle icon in the right side pan. That means android device is properly not installed on your computer or laptop.
Step 3: Press right mouse button which has yellow triangle option then you have to click on Update Driver Software option > Click on the "Browse my computer for driver software" option > Select the folder by clicking on the Browse… button now, you will get complete path of USB driver software file then click on the Next button > Now, your USB driver updating process will be start. After successfully finish the USB driver updating process, finally click on the close button.
I hope you will get required USB driver of Lava Smartphone and also helps you to easily install Lava USB driver on your PC or laptop.
If nothing helps then, please try to use another data cable...


How use ng-value and ng-model in form inputs text

Question: I'm making a form to edit information in a database, this form is working, he's taking the information depending on what I select, however it is not showing in text inputs on the page.
I know the information that i'm getting is the right information because I can see on the console and also in the attribute 'value', although not appear on the page.
This page have two inputs text:
  Name:
  <input type="text" class="form-control" name="name" rows="5" ng-value="{{ data[0].name }}" ng-model="formData.name" />

  Meeting Point:
  <input type="text" class="form-control" name="meetingPoint" rows="5" ng-value="{{ data[0].meetingPoint }}" ng-model="formData.meetingPoint" />

I want be able to see the information on the page and still send to my formData scope, but i'm very lost, is the first time that i'm using the Angular.
This is my controller:
var event = $routeParams.evento;
$scope.data;
$scope.submitForm;
$scope.formData = {};

$http.get('/api/data/event/edit/' + event)
  .success(function (data, status, headers, config) {
    $scope.data = data;
    console.log(data);
  })
  .error(function (data, status, headers, config) {
    $scope.data = data;
  });

$scope.processForm = function () {
  console.log($scope.formData._id);
  $http({
      method: 'PUT',
      url: '/api/data/event/edit' + $scope.formData._id,
      data: $scope.formData,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    .success(function (data) {
      console.log(data);

      if (!data.success) {
        $scope.errorName = data.errors.name;
      } else {
        $scope.message = data.message;
      }
    });
};

So i'm getting the event that i want, them i'm trying to show the information with ng-value, but isn't working, and also edit my formData object.
Can someone give me a hand here? :)
Thanks!!!!
Comment: You should only use the `ng-model`, it provides you with a two-way binding to the model value
Answer: ng-value="{{ data[0].name }}"

Angular DOCS:: ng-value is not appropriate for input text

Binds the given expression to the value of  or input[radio],
  so that when the element is selected, the ngModel of that element is
  set to the bound value.

You must use ng-model for input text box.
Comment: i get it!.. i can use ng-model to show and to send the editions to my server.. ok, thanks!!!
Comment: i cant.. waiting 2 min.. haha


display the multiple value in single field in drupal 7 view

Question: display the related multiple value in single field to avoid duplication in drupal 7 view
Guys help me to solve this issue.
Now it's like this.
Name -----------------------------Organization
sam --------------------------------Ministry of public Health
sam ---------------------------------It solution company
I want to display like below
Name------------------------------Organization
sam----------------------------------Ministry of public Health, It solution company
Answer: You can do this by "Rewrite results" follow the following steps.
1) Edit the first field and exclude it from display.
2) Edit the second field and click on the "Rewrite results"
3) check "Rewrite the output of this field" checkbox.
4) find your fields in the "replacement Patterns" and put it in the textarea like this [field1],[field2]
Comment: Thank you for replaying me but this is not 2 field. please check the above picture which I have uploaded
Comment: you get two records because you entered a separate node for each organization, so i suggest you to use https://www.drupal.org/project/textformatter this module to combine the organization by comma, and not to enter separate node for each organization.
Answer: 1- open your view and select ur field which is filed collections
2- select the following settings
Answer: You can use views_php module. This module adds a field to your module that its content is php code. The rows and results of other fields are also available in the php code.
Comment: While this may be a valid answer, any PHP code that can be added via the CMS is a security issue.


Como remover um diretório no Windows mesmo que esteja em uso?

Question: Tenho um serviço de banco de dados rodando em um diretório conhecido C:\meuBanco\exe\ e agora desenvolvi um atualizador deste serviço, que executa os seguintes passos:

Para o serviço
Exclui a pasta exe: rd /s /q %DIRSERV%\exe\
Descompacta o zip com o novo serviço na pasta exe

O problema está no passo 2, onde eventualmente não é possível excluir a pasta, pois está em uso.
Mas quando a atualização é executada, ela pode excluir a pasta, pois não deveria ter qualquer processo bloquando a pasta exe.
Por isso pergunto: existe uma forma de forçar a remoção de um diretório no Windows mesmo que esteja em uso?
Comment: Tente isso: http://stackoverflow.com/a/98069/5524514
Comment: Finalizar os executáveis ou arquivos que estão abertos no diretório não resolve? para finalizar com o `takkill` exemplo: `taskkill /f /im notepad.exe` aí depois apaga o diretório...
Comment: Acredito que precise elevar privilegios ao nivel do de sistema, afinal, esse recurso é por segurança,  pra ninguem apagar algo que esteja em uso e comprometer  outra aplicação que esteja fazendo este uso.
Comment: @diegofm Já rodo a atualização como administrador. Há outro nível possível?
Comment: Sim, há outros niveis de sistema acima do administrador, tanto é que existem pastas e arquivos que você, mesmo como admin, não consegue acessar no windows
Comment: @diegofm O workaround com robocopy funcionou!! Incrível. Se quiser responder..
Comment: @LaércioLopes Eu não sei quais são os executáveis (podem ser aplicativos externos), então teria que primeiro descobrir isso.
Answer: Você pode testar essas duas opções abaixo. conforme esta resposta no SOEn:

Cuidado ao executar estes comandos! Após executados, o processo é irreversível e pode causar danos a uma aplicação ou ao sistema operacional, caso seja executado em pastas do windows.

takeown /r /f [path da pasta]
cacls [path da pasta] /c /G "ADMINNAME":F /T
rmdir /s [path da pasta]

Outra alternativa para paths longos, que podem ocasionar erros com o método acima:
mkdir \empty
robocopy /mir \empty [path da pasta]

Obs.: o usuário a executar ambos os comandos precisa ter privilégios elevados de administrador.


Expected value of a product of random variables

Question: Knowing the distribution,
\begin{array}{c c c c}
& \quad    &X=1\quad   &X=-1\quad  &X=2  \\
&Y=1\quad  &0.25\quad  &0.25\quad  &0    \\
&Y=2\quad  &0\quad     &0\quad     &0.5
\end{array}
How does one calculate E(XY)?
Comment: If this is for some course, please add the `self-study` tag. If it isn't self-study, please explain the context in which your question arises.
Answer: $\displaystyle E[XY] = \sum_i\sum_j x_i\cdot y_j \cdot P\{X = x_i, Y = y_j\}$
which gives $2$ in this case.
Comment: I wonder which part of the answer the down-voter believes to be incorrect or not useful.


Erro ao usar TempData no ASP.NET 5: Session has not been configured for this application or request

Question: Estou precisando usar o TempData numa aplicação web porém dá o seguinte erro em runtime:
InvalidOperationException: Session has not been configured for this application or request.
em Microsoft.AspNet.Http.Internal.DefaultHttpContext.get_Session()

Vi em alguns fóruns que preciso habilitar alguma coisa mas não entendi direto o que. Alguém sabe como resolver isso?
Este é meu controller Home:
 [HttpGet]
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Index(Contato contato)
    {
        SendEmail EnviarEmail = new SendEmail();

        try
        {

            EnviarEmail.EnviarEmail(contato);

            TempData["Mensagem"] = "Mensagem enviada com sucesso!";
        }
        catch (Exception ex)
        {
            ViewBag.Message = "Erro ao enviar email!";
        }

        return RedirectToAction("Index");

Esse é meu index.cshtml
    <form asp-controller="Home" asp-action="Index">

            @if (TempData["Mensagem"] != null)
            {

            }

                Nome
                <input type="text" name="nome" id="nome" placeholder="Nome" required oninvalid="setCustomValidity('Insira o seu nome')" onchange="try{setCustomValidity('')}catch(e){}">

                Email
                <input id="email" name="email" placeholder="Email" type="email" required oninvalid="setCustomValidity('Insira um email válido')" onchange="try{setCustomValidity('')}catch(e){}">

                Assunto
                <input id="assunto" name="assunto" placeholder="Assunto" type="text" required oninvalid="setCustomValidity('Insira um assunto')" onchange="try{setCustomValidity('')}catch(e){}">

                Mensagem
                <textarea id="mensagem" name="mensagem" placeholder="Mensagem" required oninvalid="setCustomValidity('A mensagem é obrigatória')" onchange="try{setCustomValidity('')}catch(e){}"></textarea>

            <input class="botao_enviar" type="submit" value="Enviar">
        </form>

Meu site é um site de uma única pagina onde eu navego entre as sessões, por isso coloco esse if no cshtml para ver se o TempData está nulo e como é um redirecionamento para a mesma pagina uso ele.
Comment: Você está usando Owin?
Comment: Não cara, pra ser sincero nunca usei
Comment: Sempre usei TempData no ASP.NET mas agora no 5 tá com essa novidade
Comment: Tá, espera aí. Você está usando ASP.NET MVC 5 ou ASP.NET **CORE** (que antigamente era chamado de ASP.NET 5, ou vNext)?
Comment: Agora nesse projeto estou usando o ASP.NET 5 Web Aplication, tanto é que ainda consigo usar as tags do 5 no .cshtml
Comment: Poderia adicionar o seu código? Como está fazendo para utilizar o `TempData`?
Comment: Então é ASP.NET CORE, não MVC 5
Comment: Eu to meio perdido nessas versões do ASP.NET, toda vez que eu preciso instalar o visual studio é um padrão diferente, estava usando o ASP.NET 5 tanto é que as tags são padrão ASP.NET 5 por exempo asp-controller=""
Comment: Consegui resolver seguindo esse link http://www.mikesdotnetting.com/article/270/sessions-in-asp-net-core-1-0
Comment: Tive que adicionar duas linhas no project.json mais algumas linhas no Startup.cs, mas não entendi o por que disso
Answer: Acredito que o problema seja outro. De uma olhada se voce tem o pacote Microsoft.AspNet.Session referenciado.
Apos isso, confira a ordem o Startup.cs:
// Add MVC services to the services container.
services.AddMvc();
services.AddCaching(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession();

e tambem
// IMPORTANT: This session call MUST go before UseMvc()
app.UseSession();

// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });

    // Uncomment the following line to add a route for porting Web API 2 controllers.
    // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});

fonte: http://benjii.me/2015/07/using-sessions-and-httpcontext-in-aspnet5-and-mvc6/


Ordenar pelo nó vendas javascript

Question: Como posso fazer para que o javascript ordene este array pelo nó vendas?
[{"codigo":"produto003059","vendas":0},{"codigo":"produto003062","vendas":0},{"codigo":"produto003067","vendas":4},{"codigo":"produto003068","vendas":1},{"codigo":"produto003070","vendas":0},{"codigo":"produto003071","vendas":0},{"codigo":"produto003073","vendas":2},{"codigo":"produto003875","vendas":3},{"codigo":"produto003879","vendas":0},{"codigo":"produto003881","vendas":0}]

Existe alguma função ou comando?
Answer: Para ordenar arrais podes usar o .sort(), que passa como argumento elementos da array. Uma vez que cada elemento é um objeto tens só de dizer isso dentro do sort. Como os valores das chaves vendas são numeros basta usar na função do sort return a.vendas - b.vendas;
Presumo que esse array seja um JSON, por isso incluo o JSON.parse no código em baixo.
var vendas = '[{"codigo":"produto003059","vendas":0},{"codigo":"produto003062","vendas":0},{"codigo":"produto003067","vendas":4},{"codigo":"produto003068","vendas":1},{"codigo":"produto003070","vendas":0},{"codigo":"produto003071","vendas":0},{"codigo":"produto003073","vendas":2},{"codigo":"produto003875","vendas":3},{"codigo":"produto003879","vendas":0},{"codigo":"produto003881","vendas":0}]';

var ordenado = JSON.parse(vendas).sort(function(a, b){
       return a.vendas - b.vendas;
});

console.log(JSON.stringify(ordenado)); // dá: [{"codigo":"produto003059","vendas":0},{"codigo":"produto003062","vendas":0},{"codigo":"produto003070","vendas":0},{"codigo":"produto003071","vendas":0},{"codigo":"produto003879","vendas":0},{"codigo":"produto003881","vendas":0},{"codigo":"produto003068","vendas":1},{"codigo":"produto003073","vendas":2},{"codigo":"produto003875","vendas":3},{"codigo":"produto003067","vendas":4}]

jsFiddle: http://jsfiddle.net/8918kzvk/
Comment: Certo, e para inverter a ordem basta trocar a posição das variáveis `return b.vendas - a.vendas;`

Ordenar pelo nó vendas javascript


Permutation statistics yield different results when computed again

Question: I am doing a within-subject design experiment and trying to analyze my data. To simplify my problem, let's say that there is condition A and condition B, and I have 24 pariticipants. I want to do permutation statistics in order to test if there is a difference between condition A and B. From what I understood, there is 2^24 possible permutations, as we compute either A(i) - B(i) or B(i) - A(i) for each participant. As this is not possible to do all the permutation, I only compute N=2000 permutations but then, if I run multiple times my code, since there is always a different permutation, sometimes I can get a significant results p < 0.05 and sometimes a non significant results. This is annoying as I don't want to do "p-hacking".
My question is then : How to deal with permutation statistics yielding different results when we only do a part of possible permutations ?
I tried to read different explanation of permutation statistics and some says that 5000 permutations "is enough" but that does not solve the problem of non-determinism...
I hope that I am clear, feel free to ask for more details if needed.
Thank you !
Comment: Put `set.seed(2021)`(R) or `np.random.seed(2021)` (Python) at the top of your code; I'm sure other software packages like SAS, Stata, SPSS, and Matlab have similar commands. Then it will give the same permutations every time. As long as you don't tune the seed to give you the desired result, you are fine. (Perhaps even consider using your birthday or lucky number as the seed, so it doesn't change every year.)
Comment: Thank you for your answer. I was not sure if fixing the seed would be valid for a scientific analysis, as it involves randomization, but now that you say it, it makes sense!
Comment: 2000 values is pretty small (for all that it seems to be a common default). It made sense in the late 60s, but not at any time since then. It gives a margin of error of 0.01 (about two figures of accuracy for a p-value near 0.05) -- you can compute an estimate of the standard error of your estimated p-value easily (it's a binomial proportion) and for any application you can decide how much margin of error you can tolerate in your sample-estimate of the p-value. I tend to use 100,000 to 1,000,000 resamples (If I have to wait a minute, so what?) because I seek nearer to three figure accuracy ...
Comment: ctd ... If I have one that (for some reason) runs very slow I may do 10,000 ... but I might also then set it going overnight, since I rarely need a more precise result instantly. You can always consider saying that if your p-value is anywhere close to being within the margin of error (say within twice the margin of error) of your significance level, you should simulate much more, as long as the protocol is clearly defined before the first simulation is run so there's no danger of people thinking you had done so because you didn't like the outcome.
Answer: If you're down to setting seeds to get reproducible results from
permutation tests, something may be wrong. Maybe the sample size (e.g., your 24) is too small,
you're not using enough permutations (e.g., your 2000), the metric does not take enough uniquely
different values, or there is a programming error. Obviously, a simulated
permutation test is subject to simulation error, but in my experience,
running such a test several times with different seeds (or no seed) gives
substantially similar results on each run.
Let's take a look at the kind of simulated permutation test you are
using---for fictitious non-normal data---to see how my version of it works in R.
Suppose we have $n = 24$ differences $B - A$ as in my vector dif below:
The observed average difference is $1.67.$  Also, descriptive graphics show
the differences are right skewed. Thus they are not excellent candidates for testing either with a one-sample t test or a one-sample nonparametric Wilcoxon signed=rank test. (But, for the record,
both tests do reject that the differences are centered at $0$, the Wicoxon test with
a warning about ties.)
ad.obs = mean(dif); ad.obs
[1] 1.666667

R code for figure:
par(mfrow = c(1,3))
 hist(dif, prob=T, col="skyblue2"); rug(dif)
 boxplot(dif, col="skyblue2")
 qqnorm(dif, pch=19); qqline(dif, col="green2", lwd=2)
par(mfrow = c(1,1))

A one-sided permutation test that averages the differences after randomly switching the 24
signs shows a significant difference with P-value about $1.5\%,$
set.seed(2022)
ad.prm = replicate(5000, mean(dif*sample(c(-1,1),24,rep=T)))
mean(ad.prm > mean(dif))
[1] 0.0142  #  P-value of simulated permutation test

hist(ad.prm, prob=T, br=30, col="skyblue2")
 abline(v=ad.obs, col="red", lwd=2, lty="dotted")
length(unique(ad.prm))
[1] 3838

Two additional runs with different seeds and different numbers of permuted means
give essentially the same result.
set.seed(1776)
ad.prm = replicate(10^5, mean(dif*sample(c(-1,1),24,rep=T)))
mean(ad.prm > mean(dif))
[1] 0.01146

length(unique(ad.prm))
[1] 15437

set.seed(14)
ad.prm = replicate(5000, mean(dif*sample(c(-1,1),24,rep=T)))
[1] 0.0122
length(unique(ad.prm))
[1] 3827

Note: Here is R code used to sample the fictitious differences used above.
set.seed(426)
dif = round(rexp(24,1/5)-rexp(24, 1/2), 2)

Comment: Thank you for the answer. Maybe I don't understand it fully but isn't there an error in the permutation created ? `sample(...)` creates a vector of -1 or 1 to say if we invert or not each differences, but you take the mean of this vector of -1/1. For me it should be `mean(dif * sample(...))`
In this situation, take for instance `set.seed(14)` and `5000` permutations and you have a case when the tests fails : [here is a screenshot](https://imgur.com/a/lu6gjMv)
Did i miss something ?
Comment: Thanks for comment. Obviously, you have followed my answer carefully! You are right about the typo in the code (now corrected). I got P-values about 0.011 to 0.014 in three runs with different seeds and nrs of replications. (I used your seed and number of replications in the last run now posted.) // But I can't replicate your non-significant result or histogram. Wondering if you may have used different data.
Comment: If you had normal data with $\sigma=2$ trying to use a t-test to detect a real difference of $\Delta=2,$ with only $n=24$ observations, then you would have power only about 65%. That is, 65% of samples of size 24 will give P-value below 5% and 35% will not.  Similarly, if you generate data using my algorithm, a true permutation test (with combinatorics, not simu) will reject sometimes and sometimes not. Sim perm test will act similarly. Not mainly because perm test is (a bit) random, but because expts with 24 obs are underpowered. // BTW, my last msg should have 'perm test', not 'bootstrap'.
Comment: Oh indeed, my bad, I was using the seed before generating the data and not changing it after permutation. With your seed for the data (`426`) I cannot replicate my non-significant result, but if you try with
```set.seed(14)
dif = ...
ad.rpm = ...
```
directly, you get my previous histogram. I wonder why is that, but that "proves" that my behavior can still happen, or did I do something wrong? Thanks again !
Comment: Here is my code that do that just in case : [here](https://pastebin.com/a97JzuG1)
Comment: We get different answers because my **data** `dif` is sampled using `set.seed (426)` and your data is sampled using `set.seed(14)`. If you use my data you will get about the same P-values I did no matter what seed you use for the **bootstrap**.
Comment: Oh I see my problem, sorry. That was just a case where the two data were not significantly different... Here is a borderline case then when sometimes it is significant and sometimes not : [here](https://pastebin.com/KPqQm7w0) Did I miss anything? Thank you again.
EDIT : This is exactly my question, how to deal with varying results for permutation tests with borderline cases ( = p-values close to the significance level)