How can I learn about reasons for choosing different ways to play a chord?

Question: I was playing a song where E7 was written as 022130 as opposed to 020100 which I'm used to playing. It sounds "stronger" and "rounder" to me, similar to playing G as 320033 as opposed to 320003. I suppose the differences in feeling are caused by the order of the notes on the strings (inversions?), which notes are repeated, etc. Maybe also the musical context, but how?
My question is: What can I read or study to learn which different feelings the different ways of playing chords evoke, and why that happens?
(I'm not asking about these particular examples.)
Related: In chord progressions with F->G I often just move the F-bar instead of playing the "normal" 320003 because it's more convenient. They feel pretty similar to me, but it would be interesting to know how they differ, i.e. what I'm sacrificing/changing?
Answer: This is a great question. If you keep playing you will spend a long time trying to answer it for yourself.
There are many factors, and in the end such decisions are largely personal as @Tim has pointed out in his answer. In and of themselves chords don't contain any emotional content, and you might notice that the same chords feel different in different contexts. It may be helpful to attach terms like "jagged" or "buttery" or "anxious" to chords, but recognize that this is personal and provisional. Chords have much subtler colors than can be captured by such simple names. Learn to listen carefully and to decide for yourself how chords make you feel in different settings. To a certain extent this seems to suggest that you are on your own when trying to understand how chords work and how to choose from the many ways to play any single chord. But there are some things that might be helpful for you to think about.
One of the things that I was taught early on is that economy of motion is important. That means that, as a general principle, it is good to find ways to play what you need to play which involve small movements rather than large movements. This thinking can lead to a way of playing which is easier to execute, and can also help to find ways of connecting different chords smoothly.
Part of this is physical: make it easier to play by finding convenient chord voicings (this is particularly helpful when playing fast chord changes). Often there is more than one fingering for the same chord voicing, and the same principle applies: choose the fingering that is convenient, that is, choose the fingerings that make it easy to get to where you want to go from wherever you are coming from.
Another part of this is sonic: voice leading is the discipline of connecting the notes in each chord to the chord which follows. Further, different chord voicings have different sounds, and you may choose one voicing in a particular instance because you like the sound. Then you may choose the next chord voicing because it is a logical movement after the first chord.
These concerns of the physical disposition of the notes of a chord voicing on the fretboard, the physical movements involved for the player, the particular sound a particular chord voicing makes, and the way that chords and harmony are moving in the music are all intertwined. It is a lot to take in. Keep thinking about it and trying to understand what works for you.
Here are some examples using a ii - V7 - I chord progression in A, that is: Bmin7 - E7 - A.
$A.2.$D.0.$G.2.$B.3.$e.2 | $E.0.$A.2.$D.0.$G.1.$B.0.$e.0 | $A.0.$D.2.$G.2.$B.2.$e.0

$A.2.$D.0.$G.2.$B.3.$e.2 | $E.0.$A.2.$D.2.$G.1.$B.3.$e.0 | $A.0.$D.2.$G.2.$B.2.$e.0

First, for economy of motion to the final A you might prefer one of these over the other:
%X/X.0/0.2/2.2/1.2/3.0/0[A]
%X/X.0/0.2/1.2/1.2/1.0/0[A]

There is no correct answer here, other than that it is what works best for you. You should be able to play A both ways so that you can choose when circumstances permit.
Also note that in the second example the note that is under the pinky (D) is the same for the first two chords, then moves down a half-step in the final chord. This note is the 3rd of the Bmin7, the 7th of the E7, and after moving down to C♯ is again the 3rd of the A. This note movement is satisfying, and I would probably favor this second version of the above two examples. Or notice how strong the movement of this pair of notes from the second example is (with contrary motion when changing to the final chord):
$G.2.$B.3 | $G.1.$B.3 | $G.2.$B.2

You can combine these notes with the roots of the chords to get a complete picture of the underlying chords:
$A.2.$G.2.$B.3 | $E.0.$G.1.$B.3 | $A.0.$G.2.$B.2

There are so many things that we could talk about, even with just this simple example. What about Bmin7 in second inversion, E7 in root position, AMaj7 in second inversion? The important thing is to listen for yourself and decide which you think sounds best.
Here is another example, this one is Bmin7 - E7 - AMaj7:
$A.5.$D.7.$G.4.$B.7 | $A.5.$D.6.$G.4.$B.5 | $A.4.$D.6.$G.2.$B.5

This progression uses a Bmin7 in first inversion, an E7 in third inversion, and finally an AMaj7 in first inversion again. You might find these particular chord voicings challenging to play, they require a bit of a stretch. Notice how different the same chords used in the first example sound now that they are played without the root notes in the bass. Also notice the sound of a minor 2nd between the 7th and the root of the AMaj7 chord. This minor 2nd gives this voicing a distinctive sound:
$D.6.$G.2

Notice how the notes lead to each other. This time the note under the second finger (D) is the 3rd of the Bmin7, remains the same for the E7 where it is the 7th of the chord, then moves down a half-step to C♯ which is the 3rd of the AMaj7. Also, the note under the third finger (A) is the 7th of the Bmin7, moves down a half-step to G♯ which is the 3rd of E7, then stays in place becoming the 7th of the final AMaj7.
It turns out that the way that 3rds and 7ths of chords move around is pretty important.
If you can't play the last example, it is a bit difficult, try to play it higher on the neck where the frets are closer together. Here it is in D (Emin7 - A7 - DMaj7):
$A.10.$D.12.$G.9.$B.12 | $A.10.$D.11.$G.9.$B.10 | $A.9.$D.11.$G.7.$B.10

Note also that this chord can be thought of as a Bmin7 in first inversion, or as a D6 in root position:
%X/X.5/2.7/3.4/1.7/4.X/X[D6]
%X/X.5/2.7/3.4/1.7/4.X/X[Bmin7]

It is really common to see the above voicing used as a D6.
Comment: Thank you so much! I learnt a lot from this answer. The example was very helpful. Thank you!
Comment: What happened to the chord fingerings/tabs in this answer? They look like this to me $D.6.$G.2
Answer: Reasons for choosing a particular inversion and/or voicing, particularly on guitar, are rather personal than anything else.
Any resource will have been written with that in mind. So it won't help much. You're better off using your ears and choosing whichever you think sounds best, and possibly, as you mention, is easier, more effective to get to and from.
Be aware that those two E7 shapes can be combined as in 020130. Certain voicings suit certain styles in a way, and the more open G always sounds less harsh than the one using 2nd string 3rd fret, to me. But a couple of guys I play with occasionally say that's the 'proper' way to play a G. Not a good mindset, but what do I know?!
The other factor which creeps in regarding inversions is that it's generally accepted that the root position (root note lowest) sounds most stable, with the 2nd inversion (3rd with 4 note chords) sounding weaker or not so convincing as the rest.
Regarding your last para: there's only subtle differences between certain chord shapes. We tend to catch the highest and lowest notes from the sound of a chord, and with guitar, it's often difficult to discern the notes in between. With open strings versus fretted, though, there is more of a sound difference than a note make-up difference, thus the open G will tend to sound different from the barred G. That and when you're playing a 'pulsed' rhythm, using the fretting hand to stop strums short, it works far better on barred chords, and also if the rest of the chords are barred, the sound is more consistent.
Comment: The relevance of voicing and inversion probably depends on the style of music the asker is trying to play. In my experience (and according to Wikipedia, https://en.wikipedia.org/wiki/Voice_leading), voice leading is critical in classical music, and less so in jazz and modern popular music. Just something to bear in mind. Of course, as you mention, the ear is the real source of truth.
Answer: Two other things to consider when choosing chords shapes:

Wrist and hand positioning. The same chord progression may be more comfortable and reliable in a certain position or voicing than others by minimizing the amount of reaching or uncomfortable wrist positions. This will help you voice the chord fully by having all the frets held properly, and reduce the possibility of injury long term. When you are practicing, taking a moment at each chord to look at your hand, wrist and arm, and ask yourself - am I squeezing too hard? Is my wrist in a comfortable position or twisted? As you learn more possible voicings for each chord, you can choose finger patterns that are appropriate for your hand size and go well together in the progression.
Voice leading. Voice leading is the practice of considering each note in a chord, and how it moves to the notes of the next chord. This technique is often described as making music sound 'smooth' or 'clean'. By moving as few notes as possible when changing chords, the chord change will have a more coherent, gentle sound. Changing lots of notes by, for example, moving a barre chord up and down the neck, will sound more dramatic and jarring. Both are valid choices depending on the sound you want, but that is also something to consider when picking what finger pattern to use for a chord.
Comment: Your no.1 is so true! I can never understand why open C an open G chords are taught (by some) so early. Wrist and hand positions are so different between C and G, changing, for a beginner, is not easy.
Comment: While I'm pretty much a "hack" at guitar, these are also the major reasons for selection of chord voicings/inversions when playing piano accompaniment (as opposed to having to play with the melody included).
Answer: Learn to play a lot of different songs from different genres. Most musical elements do not carry a lot of feeling on their own, the context is key. So you won't be able to just play different chord voicings and understand how they work in isolation. What you want to do is learn to play as many chords and voicings and patterns in different contexts.
The short answer is, study and practice and study and practice and then study and practice some more.
Answer: There are lots of online resources if you search for 'alternative chord shapes' and similar.  Here's one, picked at random.
https://www.guitarhabits.com/10-ways-to-play-the-most-beautiful-open-chord-shapes/
Yes, the inversion (which note of the chord is lowest) and voicing (notes close together or spread over several octaves) make a difference.  Guitarists can also choose to use open strings in some chords, which gives a particular effect.
You can learn the various possibilities.   Only you can decide what feelings they evoke though.  Have fun exploring!
Comment: Thanks for your answer Laurence! I can figure out different chord shapes. I'm looking for a resource on how the different shapes feel and why they are used. Similarly maybe to how everyone knows how minor chords or dominant 7th chords or diminished chords feel. I'm new to music and I'm sure I could go exploring blindly and would have figured out that minor chords sound sad by myself, but I believe it's helped me a lot to hear these ideas already condensed.
Comment: Minor = sad is a glib over-simplification.   As would be any other description of how a particular chord 'feels'.
Comment: I appreciate your open-minded approach and I'm sure it's healthy for experienced musicians or people who have grown up around music, but I'm hoping for an answer other than "figure it out yourself" to help my development.
Comment: I'm rather partial to the sound of the resolution 022434 (E7) into x02225 (A) but didn't notice those forms on that page of beautiful open chords.
Comment: I understand.  You want a set of rules to follow.  I'm afraid there isn't one.  And, as you've seen, when people attempt to give you what you want, they get impossibly complex and subjective.
Comment: @supercat - sounds nice! And it's simply open D7 to open G, moved up a tone.
Comment: @Tim: Upper strings are moved up a tone, but the bottom string is open.  I wonder why I haven't noticed anything else using those chords, because they're awesome (I was inspired to discover them because in my own Flatfinger (G-D-d-f-g#-b) tuning, a D7-G transition is easy to play (x-0-4-4-4-7 to x-5-5-6-6-8) but sounds awesome; the E7-A transition in standard isn't as easy to play, but retains the most important parts of the voicing (the ascending V-I in the root, and the tritone that resolves outward).
Answer: The answers so far are quite good, but they don't specifically address your E7 question (IMO). E7 is an interesting chord because of the tension between the D and the E notes in the chord. When you play 030100, you have an open D, but it is fairly low and isolated, so the tension is minimized. But when you play 022130, the D and E sound only a whole step apart, maximizing the tension between the two. So when you resolve into an A chord, the greater tension has a greater feeling of resolution.
I prefer G as 320033 because my (cheaper) guitars have intonation problems with an open B. My middle finger tends to mute the lone B, so I end up with the "power" chord of 3x0033. If I am writing in the key of C, however, or the melody starts on a B, I will play 320003 to create the harmonies I want in the song.
In other words, try all the variations you know (and learn or figure out more) to see what sounds best to your ear. You might even try playing the same song in multiple keys! Remember, you're an artist and the colors in your palette are the voicings of your chords.
Comment: Good answer. In particular, for the resolution to (standard-voiced) A, the open-d-string version doesn't really make any sense voice-leading wise, because the seventh is resolved _upwards_ though classically, it strongly wants to resolve downwards as it does in the high-d version (to c♯). — Regarding those intonation problems – you're aware that the major third in 12-edo tuning is [too high "by design"](https://en.wikipedia.org/wiki/Temperament_(music))? This is particularly obvious when it rings out on open strings and/or doubled; the problem may have nothing to do with the instruments.
Answer: When you are deciding what chord version to use, I think you can take into consideration the melody line.
For example, I also prefer 320033 - it is almost a power chord (5 of 6 strings are playing 1st and 5th) so it sound pretty cool. However, some time ago I played one song and realized that 320003 sound much better there. I understood why it happens this way when I tried to play a melody line alone. It turned out that it starts with the 3rd (i.e. B note). Since in 320003 this note occurs twice, it sounds much better in this song.
So when you play a song, try to repeat/highlight the notes from the melody line in your chords.
Answer:
What can I read or study to learn which different feelings the different ways of playing chords evoke, and why that happens?

The simple answer: You can't.
It's very easy to look at whether your lowest note is the tonic, or looking at whether the chords give you a particular bassline or pedal notes, or anything like that.  That's all stuff you can learn with theory.  What it can never tell you is how it feels.  And that's because it's an entirely subjective experience for every person.
For your E7, having the seventh on the B string makes that a higher pitch.  Since guitars will generally emphasise those high-mid notes, and the unwound strings will generally sound more "jangly", that can give you a more "obvious" seventh sound.
For your G, the 320003 version can sound a little more "mushy" on the low end with the B on the A-string, which becomes an issue with electric guitar.  The classic barred power-chord (slide up your F) tends to avoid that problem.  However the barred version generally uses higher-pitched notes within the chord, which you'll notice sounds different.  The open strings on 320003 will also tend to sound more "jangly", which is another factor.  As for 320033, that B on the A-string is less prominent, which makes it sound more like G5 (a power chord), which generally will sound a bit harsher.
Those are some generalisations about how the different voicings might sound.  For how you feel when you play them - to quote the Hollies, "I can't tell you, but I know that it's mine". :)
Comment: With a little help from my friends, I thought it was the Beatles.
Answer: You can change the notes in a chord, but not all notes are equally important.
The most important notes to indicate the "color" of a chord are the third (telling you if it's major or minor) and the seventh (telling you what type of seventh chord this is). What you're doing with the two E7 voicings is moving that D, which is the seventh, up an octave. In general you want to avoid having more dissonant intervals (like a 7) in the lower register: it gets muddy, especially because you are not playing the third (the G sharp). If you keep the more dissonant intervals in the higher register, you can get away with playing chords with a lot more color (dissonance) to them.
You want to think about what is musically happening as you play chords different ways, but there's a problem: you're playing guitar, a uniquely beautiful and uniquely frustrating instrument. The best book I've found about how to choose chord voicing for musical effect is The Jazz Piano Book by Mark Levine (not the theory book, although it's also good). Each chapter introduces one new idea on how to choose what notes to play (or leave out) of a chord, with tons of examples listed. The benefit to learning theory on piano (even the cheapest midi or toy) is that you can make a change and hear it immediately: I wasted years trying to get ahead on guitar because I couldn't play (and hear) the examples. For guitar books, Ted Greene's Chord Chemistry is sort of related, as are any number of books on getting started in jazz guitar (I also like Jody Fisher's books). No guitar book is as clean and simple as the Jazz Piano book, such is the nature of the guitar.


Como fazer uma consulta para saber a médias de pessoas por dia de uma semana

Question: Olá, gostaria de saber como fazer uma consulta(Query) no banco de dados Oracle para saber: Qual a quantidade média de hospedes por dia de uma de semana qualquer.
Segue abaixo o script do banco:
CREATE TABLE APP.HOSPEDAGENS (
      hsp_id number(6),
      hsp_checkin Date,
      hsp_preco_total number(8,2),
      hsp_checkout Date,
      hsp_cli_id number(6),
      hsp_qua_id number(6),
      CONSTRAINT pk_hsp_id  PRIMARY KEY(hsp_id)  );
ALTER TABLE APP.HOSPEDAGENS ADD FOREIGN KEY (hsp_cli_id) REFERENCES APP.CLIENTES (cli_id);
ALTER TABLE APP.HOSPEDAGENS ADD FOREIGN KEY (hsp_qua_id) REFERENCES APP.QUARTOS (qua_id);

Answer: É possível retornar o dia da semana usando a função to_char, formatando a data com o parâmetro 'd', que retorna o dia da semana. Assim é possível agrupar a consulta pelo dia da semana e realizar a contagem, ex:
select to_char(hsp_checkin, 'd') as DIA_DA_SEMANA,
       count(*) as total
  from HOSPEDAGENS
 group by to_char(hsp_checkin, 'd')
 order by 1

Comment: Exemplo no sqlfiddle: http://sqlfiddle.com/#!4/ff2030/1/0


Persian language support in PHP/MySQL web application

Question: I'm building a PHP/MySQL web application and I need to have persian language support besides english, french and german.  Can you guys give me some advice regarding this topic? What encoding should I use in order to match all three languages?
Thank you.
Answer: Looking at a Persian Website should give you some clues. utf-8 seems to be fine (and certainly will be for German/French), but you'll need to set the text direction to rtl (right-to-left) for Persian.
Comment: And I can set the text direction using css. Thanks.
Comment: you can set `dir=auto` to browser the the direction automaticaly


Building Docker images for multi environment support

Question: I'm building docker images for our servers, and I'm looking for the best practices related to multi environments support, when creating the DOCKERFILE(s).
The main purpose of the servers is to run LAMP on top of Centos 6, and I want to make the DOCKERFILE(s) as generic as possible to support both development and production environments.
The images will have lot of common configurations / utils, and some differences.
Differences for example:

Production only: monitoring tools, AntiVirus and different LAMP configurations
Development only: xdebug, profiling utils and different LAMP configurations

I thought about using something like the following structure:

Customized Base OS (C1)

Prod. Base OS (C1E1)
Dev. Base OS (C1E2)

Web image (httpd, apache..) (C2)

Prod. adjustments (C2E1)
Dev. adjustments (C2E2)

DB image (C3)

Prod. adjustments (C3E1)
Dev. adjustments (C3E2)

Data image (C4)

Prod. adjustments (C4E1)
Dev. adjustments (C4E2)

Samba image (dev. only) (C5)

but as you can see, it is impossible to do it with the current inheritance mechanism, and even if it was, it is not maintainable.
I can't find a way to use ENV conditions within a DOCKERFILE (only with Linux based conditions in the RUN command for example).
At the moment I'm using the following structure:

Base Image (Common things, such as LAMP, utils..)

Dev. Image (Dev. specific utils / configuration)
Prod. Image (Prod. specific ...)

Are there any best practices for the above?
Duplication of images (double maintenance) is the only possibility?
Answer: One of the concept of Docker is to have the same environment - if you have a different environment in production than dev, then you don't know that it will really work with full total certainty when the application is moved into production.
From docker.com:

Eliminate Environment Inconsistencies
By packaging up the application with its configs and dependencies
  together and shipping as a container, the application will always work
  as designed locally, on another machine, in test or production. No
  more worries about having to install the same configs into a different
  environment.

That said, of course production and dev will have differences, but that should be mostly in terms of application configuration - for example, the dev instance would not send out emails to customers but rather to a dummy mail box, etc.
I don't think it would be the right thing to do to have so much difference between production and dev as what you go over in your post.
As for the difference between the dev and production configuration (like the example I gave above), I personally see two workable ways of doing it.

In Dev, a Dockerfile which overwrite certain configuration of a common base for both production and dev.
Your container runs something - starts httpd, etc. The script that starts the process would first pull the config from Git or whatever repository, based on an environment variable (e.g. docker run ... -e RUNAS=PROD ...) - this is what I do. In my case, running a container for Tomcat, the Tomcat start up scripts simply downloads the war file version based on an environment variable (e.g. -e VERSION=current) and pulls from Git the configuration files based on a variable that defines whether it's production or dev (-e RUNAS=DEV).


Hide option Generate automatic URL alias for all languages on user register form?

Question: Do I need to write a hook or may be I can hide this using amdin interface?
I am using Pathauto i18n, LoggingToBoggan.
The option "Generate automatic URL alias for all languages" is displaying on user register form, and my users can't understand why. I want to hide it only on register form
this code is not correct and does not work:
function my_user_register_form_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  /* hide Generate URL alias for all languages */
  if (isset($form['pathauto_i18n_status'])) $form['pathauto_i18n_status']['und']['#access'] = FALSE;
}

Comment: Are you sure your hook is correct? Try a generic `hook_form_alter()` and `dpm($form_id)` to make sure.  Or just `die('yep')` in your hook.
Comment: the name of my module is: my_user_register_form. I've tried to add field like in field api docs "I agree terms.." and it displayed. so the name is correct. but the comand is not correct now
Comment: Is `['und']` supposed to be there?
Comment: i tried both with and without und
Answer: You can use CSS to hide it or set the option's #access value to false using a custom module.  The first will hide it but leave it available to be ticked, the second will completely remove it from the page.
Comment: thank you. this do not work for me: function my_user_register_form_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  /* hide Generate URL alias for all languages */
  if (isset($form['pathauto_i18n_status'])) $form['pathauto_i18n_status']['und']['#access'] = FALSE;
}
how to write a code?
Comment: Too hard to read in a comment mate, if you've chosen to go that way, edit your question or ask a new one.


What is the difference between grouping overlaps and elisions?

Question: I am reading "A Generative Theory of Tonal Music" by F. Lerdahl and R. Jackendoff and I don't understand the difference between grouping overlaps and elisions (this is explained in section 3.4).
The authors use visual forms to explain it, and it seems clear that an overlap happens when the end of a grouping structure is also the beginning of the next grouping structure and an elision happens when something is missing in one of the grouping structures. But when I look at the elision's musical example (3.26), the D (m.16) chord - which is the end of a grouping structure and the beginning of another one - is there and has its function in both grouping structures. So I don't understand why it isn't a grouping overlap.
Because of this example, I don't understand what is the difference between these two concepts. Can someone help me understand this?
Comment: Seeing this question reminds me that I want to read that book sometime. Unfortunately, that means I can't help at the moment. But now I'm curious about the answer.
Answer: Let's start with what overlaps and elisions have in common have in common which is they both are the end of one grouping section and the start of another so the overlap will function in both (as noted how the D in the elision). How they are different though is the that in the overlap the transition for the transition is seamless as the start and end of the grouping line up very well. The elision however the end of the one grouping section and the start of the other class a bit. It's not completely different in nature, but contrasting with some aspect of the other grouping section. Figure 3.29 with the two hexagons with overlapping sides and figure 3.30 with the square and triangle intermingled represent the overlap and elision respectively.
Let's look at both examples in the book to break down the differences.
Overlap Example:
In the overlap example from the book shown below, it's easy to see how measure 1 and 3 are the exact same and how the first beat of measure 3  resolves from the end of measure two and restates the previous grouping system at the same times.

Elisions  Example:
The elision example is a little bit easier to listen to than look at as the contrast in the groupings is extremely easy to hear. In measure 13 to the end to measure 15 we hear the statement of one idea (grouping system) which resolves in measure 16, however measure 16 musically is very different in dynamic, texture, and overall feel. The author even explains in the paragraph above figure 3.27 that the fortissimo in measure 16 elided the the last event of the previous grouping system. The D obviously functions in both, but the idea of each grouping system is very different.

Check out the score on IMSLP and listen to the recording of the piece to hear what it sounds like. On the video below the section in the book occurs from about 2:15 to 2:40 and for the IMSLP score the section can be seen on page 3.

Not only does the fortissimo give you a sense of a new section while the previous section is ending, but the instrumentation changes also and the new grouping section feels very different.


Do classical singing techniques make low notes harder to sing?

Question: I've been thinking about singing low notes and classical technique.
I sing at church and some melodies go from C3-C4.
The other men seem to have no issue with that range. I am not sure they use as much classical technique as I do.
When I use classical techniques E3-E4 feel much easier.
I feel that C3 is hard to sing if I use proper classical techniques.
C3 felt easier before I took classical singing lessons.
Do classical singing techniques make low notes harder to sing?
Comment: It might just be that you can't produce the level of tone on the lower C that you can on the higher notes, now you've started to train. You're probably also more aware of the pitch and tone you're producing, so you're singing harder to achieve it.
Comment: Lessons on any instrument, including voice, develops both our ability on the instrument or voice **and** our ears. So perhaps your sound on C3 hasn't changed that much and instead your awareness of your weakness on C3 has developed as you've taken lessons. It's also possible that proper technique makes some things "more difficult" but only because it's easier to do those things *with poor technique*. So do you want to sing C3 easily or do you want to sing it very well, with good tone, etc.?
Comment: It feels much lower after I have been taking  singing lessons. Proper techniques makes lower notes harder it seems. So for church  music classical techniques won't work?
Comment: Not an answer, but an anecdote: I know a few people (men and women) who've said similar things. They've said their low range has become more difficult to sing in since they started taking lessons. They also believe the tonal quality of their low range has worsened. I also know a former classical singer (with a degree in music/voice) who said she used to be able to sing much lower, but lost all of her notes below A3 after classical training. Apparently it rebalances the voice
Answer: "Proper" technique should enable you to sing both high and low. But often beginners will have problems to adapt their vocal configuration for these different situations.
Essentially you need to adapt the resonance and how much the vocal muscles vibrate (as compared to only the vocal cords vibrating). The more the vocal muscle vibrates the higher the mass gets, which will result in a more powerful, heavier and lower voice.
I suppose you are currently keeping your voice in a configuration suited for middle range to high notes, which will essentially make it impossible to sing lower notes.
Comment: What is the definition of middle range?


Least square fitting - exponential curve - negative $y$ value

Question: I need to fit an exponential curve through a given dataset.
The curve is defined by: $y=A\exp(Bx)$ so I need to estimate $A$ and $B$.
However my $y$ values are all negative.
I tried using Least squares fitting as described here
The problem I have is the fact that the formula uses $\ln(y)$ which returns NaN for a negative value.
How do I get around this problem?
Can someone recommend a good source to read about this fitting approach?
In advance thank you for your help.
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: If $y$ values are all negative, $-y$ values are all positive. Just handle the problem of $$-y=-A \exp(Bx)$$
$$\ln(-y) = Bx+\ln(-A)$$


Settings.canDrawOverlays for API < 23

Question: Since I can use Settings.canDrawOverlays to check if the user granted this permission on API >= 23, how I can check if the user have it on older APIS?
Does this permission is automically granted on API < 23 and no need to check for it?
Currently, I start my service only on API 23+ after the permission are granted.
@SuppressLint("NewApi")
    public void checkDrawOverlayPermission() {
        if(Build.VERSION.SDK_INT >= 23) {
            /** check if we already  have permission to draw over other apps */
            if (!Settings.canDrawOverlays(this)) {
                /** if not construct intent to request permission */
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                /** request permission via start activity for result */
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                startService(new Intent(this, ChatHeadService.class));
            }
        }
    }

But what if the user is on API <= 22? How I can make sure the application wont crash and my service will start?
Comment: There is no need to ask for this permission below Marshmallow so it is safe to run your service on those systems. You can draw overlays by default there.
Comment: Cool thank you@ @mhenryk
Comment: Of course you need the permission in manifest but that is true for every platform and I assume you have that covered. For reference it is the __ permission
Comment: also ,when you publish your app and it will be signed by Google play store the permission is granted automatically.
Comment: Try this it may be work stackoverflow.com/a/41221852/5488468
Answer: Overlay permission is only required for Marshmallow (API 23) and above. In previous APIs this permission is provided by default.

Settings.canDrawOverlays for API < 23


C - stack implement, free memory error

Question: i tired to implement a stack using a linked list, so i did it as global and i made some stack functions (push, pop, isempty)
isempty and push work great,
but i got problem with pop function, well basiclly it work to but i dont know why when i try to free the memory of the node i poped (after saving the data), its not working and cause an error.
if i just delete the line of "free" in pop function it work great but you know the problem here i have to free the heap memory after using it...
so what can i do?
there is some of the code:
#include <stdio.h>
#include <stdlib.h>

struct stack
{
    int data;
    struct stack* next;
};
struct stack* top = NULL;  ///stack is global, so push and pop can use it.

int isEmpty()
{
    if (top == NULL)
        return 0;
    else return 1;
}

void push(int x)
{
    struct stack* temp = (struct stack*)malloc(sizeof(struct stack*));
    if (temp == NULL)
    {
        printf("Error! no allocation!!");
        return;
    }
    temp->data = x;
    temp->next = top;
    top = temp;
}
int pop()
{
    struct stack* temp;
    if (isEmpty() != 0)
    {
        temp = top;
        int x = top->data;
        top = top->next;

        free(temp);
        return x;
    }
    else
    {
        printf("stack is empty nothing to pop");
        return -1;
    }
}

int main()
{
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    push(6);
    push(7);

    int cur;

    while (isEmpty())
    {
        cur = pop();
        printf("|%d|--->", cur);
    }

    printf("\n");
    return 0;
}

Comment: `struct stack *temp = malloc(sizeof *temp)`
Comment: `struct stack* temp = (struct stack*)malloc(sizeof(struct stack*))` -- you are allocating the size of a pointer to a stack and not the size of the stack itself.  Also casting the results of `malloc` is frowned upon.
Comment: "stack is global, so push and pop can use it." that is a very wrong reason to have a global. But then again, there wouldn't be any good reason to have it global.
Comment: also your `stack` is really a node. Just saying...
Comment: i changed the `sizeof(struct stack*)` to `sizeof(struct stack)` and now its work thanks
Comment: also what do you mean as not good reason to have it gloabl? why? you have a better way of make it nongloabl? i cant figured it cause i dont know what to do with the head...
Answer: This your code corrected you have a mistake when you pop your isempty() was inverse and you allocated the pointer and not your structure when you push
To clarify I inverse your isempty it was not logical that it return 0 (false) when it was empty
#include <stdio.h>
#include <stdlib.h>

struct stack
{
    int data;
    struct stack* next;
};
struct stack* top = NULL;  ///stack is global, so push and pop can use it.

int isEmpty()
{
  return top == NULL;
}

void push(int x)
{
    struct stack* temp = malloc(sizeof(struct stack));
    if (temp == NULL)
    {
        printf("Error! no allocation!!");
        return;
    }
    temp->data = x;
    temp->next = top;
    top = temp;
}
int pop()
{
    struct stack* temp;
    if (!isEmpty())
    {
        temp = top;
        int x = top->data;
        top = top->next;
        free(temp);
        return x;
    }
    else
    {
        printf("stack is empty nothing to pop");
        return -1;
    }
}

int main()
{
    push(1);
    push(2);
    push(3);
    push(4);
    push(5);
    push(6);
    push(7);

    int cur;

    while (!isEmpty())
    {
        cur = pop();
        printf("|%d|--->", cur);
    }

    printf("\n");
    return 0;
}

Comment: thanks man, im use to c++ and there you have bool types in C im a little bit rust, anyway you have any idea how to change my code so the stack wont be global? i tried many ways but its allways crush...
Comment: In c in general we give the stack in parameter. Behind the c++ it is the same things the stack is given in parameter but it is hidden for the developper stack::pop() ==> pop(stack)

C - stack implement, free memory error


having compiler error on Eclipse that is impossible to have

Question: I'm currently writing some code on Eclipse, but strangely, I got a compile error
And this is the code I have
import java.util.*;
import java.io.*;

public class Main{
    public static void main(String[] args) throws IOException{
        System.out.println("What is happening?");
    }
}

Then I thought might just be some wrong with my code, but:

Error:
- Syntax error, insert "}" to complete InterfaceBody
- Syntax error on token "Invalid Character", interface
     expected

Now I have no code, but it still says I did some wrong? So what happened? The file I have is not an interface. Nor I even have any characters, why did I get this error message?
BTW: when I have nothing written on another file, it works fine:
Comment: So both `Main.java` and `New.java` says "0 bytes"? Then try to clean the project: Select the `Project` pull-down menu, select `Clean...`, check `Clean all projects`, click the `Clean` button. --- If that fixes it, make sure `Project` > `Build Automatically` is has a checkmark next to it.
Comment: Please don't post images of code; copy them into your post and format them appropriatly.
Comment: I think he configured the main method to be in the Main.java file, which is not there if it is empty. About your comment: the compiler does not throw an error if the file is empty, but the .class file will not be created.
Comment: Then create a self-answer, explain how you fixed the problem, so others with same issue might find it. Then accept the self-answer. Might even give you the [`Self-Learner`](https://stackoverflow.com/help/badges/14/self-learner) badge.
Comment: @tibetiroka my code is not even important, I just want to show that I'm getting this error even when I have nothing written...
Comment: An empty class is not valid for the compiler
Comment: Setup a fresh project and check if the error is still there.
Comment: @tibetiroka It worked on another file... QAQ
Comment: @tibetiroka I tried it out and my eclipse don't throw an error when the file is empty
Comment: @Alex "Setup a fresh project and check if the error is still there. " how to do that? Do I just reopen my eclipse?
Comment: If you right-click `Main.java` and select `Properties`, what is the value of `Size:`? I bet it is not "0  bytes".
Comment: @Andreas I sorry, but it is 0 bytes
Comment: If you use mac this might be relevant: https://stackoverflow.com/questions/7129371/syntax-error-on-token-invalid-character-delete-this-token
Comment: @tibetiroka but I don't even have anything... T_T
Comment: @lierwu The problem is in your main.java, not in the empty file (if I understood that correctly)
Comment: @tibetiroka, yes, but the answer, it said: "You copied the source from Windows to the Mac." I don't even have anything...
Comment: @Andreas wow, thank you, it worked!
Answer: I got this problem before and it was caused by the characters inserted by my input type language when it is not English. So please make sure your input type language is English when you use Eclipse.
Comment: All of them were English and it did not even work on an empty file. But anyway thanks.
Answer: If the eclipse said zero bytes, then go to the project

Click Clean and check the box said: "Clean all projects"

Hit clean, and that would solve the problem
Answer: The most likely issue is that you have a non-printable character in your source file, which the Java compiler then rejects.
If you open Terminal, and look at the file with xxd (a hex viewer) you can see the file's contents in hex and look out for odd characters. 0a is a newline, possibly 0d as well, and space is 20 with text in the 40-50 range and 60-70 range for upper and lower cases.
Most likely you've got a non-breaking space or a BOM byte identifier in the file somewhere which is causing the problem.
It could also be the case that Eclipse thinks the file's content type is something else (e.g. EBCDIC) and thus it looks odd -- you can check what the file encoding is (usually defaults to UTF-8) with Edit - Set Encoding. There's also a 'Show whitespace characters' in Preferences > General > Editors > Text Editors, which can sometimes show where the problem lies.


Cipher suites supported by TLS1.1. and 1.2

Question: We have SSLv3 disabled in DataPower. I ran sslscan to check what all cipher suites can be used currently during SSL handshake.
In the sslscan output, I have found out that below cipher suites are being accepted.
TLSv1  256 bits  AES256-SHA
TLSv1  128 bits  AES128-SHA
TLSv1  168 bits  DES-CBC3-SHA
TLSv1  128 bits  RC4-SHA

Preferred Server Cipher: TLSv1  256 bits  AES256-SHA

I then, disabled TLS1.0 on DataPower (server) and ran the sslscan again. The result was not what I was expecting.
All the ciphersuites including the ones which were accepted during handshake over TLS1.0 are being rejected.
How would I come to know, which cipher suits my server will accept if I disable TLS1.0?
Comment: This is really a question for serverfault (where you should specify what software you're using). If you want to know what cypher suites you can use with OpenSSL (one of the implementation of TLS), you can go there: https://www.openssl.org/docs/manmaster/apps/ciphers.html
Comment: You also might want to check the [appropriate RFC](https://www.ietf.org/rfc/rfc5246.txt).
Answer: Your output only references TLS 1.0, and disabling it refuses those disabled TLS 1.0 choices as it should. Refer to the DataPower references and documentation to support TLS 1.1 and TLS 1.2 as well as configuring cipher suites. Start with checking your firmware version and properly upgrading to better support the latest TLS configurations.
Here is a reference for DataPower supporting TSL 1.1 and TLS 1.2 by default in firmware version 6. Your current version may not support anything but TLS 1.0, and not allowing yet to configure TLS 1.1, nor TLS 1.2. http://www-01.ibm.com/support/docview.wss?uid=swg21578730 references specific crypto configurations to get granular enough to resolve issues within each TLS version, such as beast.
Once upgraded and configured re-run sslscan, or alternatives if you would like to compare against sslscan such as testssl.sh.


Elementary way to show $\mathbb{Z}[e^{2 \pi i / 5}]$ and $\mathbb{Z}[X] / (X^4 + X^3 + X^2 + X + 1)$ are isomorphic

Question: I'd like to show that $\mathbb{Z}[e^{2 \pi i / 5}]$ is isomorphic to $\mathbb{Z}[X] / (X^4 + X^3 + X^2 + X + 1)$.
I'm thinking about applying the isomorphism theorem to
$f:\mathbb{Z}[X] \to \mathbb{Z}[e^{2\pi i / 5}], X \mapsto e^{2\pi i / 5}$.
Showing that $\operatorname{ker}(f) \supset (X^4 + X^3 + X^2 + X + 1)$ is straightforward:
$\operatorname{ker}(f)$ is prime, and $X^5 - 1 = (X - 1)(X^4 + X^3 + X^2 + X + 1) \in \operatorname{ker}(f)$, but $X - 1 \notin \operatorname{ker}(f)$, thus $X^4 + X^3 + X^2 + X + 1 \in \operatorname{ker}(f)$. Alternatively, and even more elementary, plugging in the value verifies that it is in the kernel.
Is there a quick way to show the reverse? Or is there another, better way to show it?
(I can't comment, so I have to answer to comments in this way: Showing irreducibility by comparing coefficients is possible, but how would it help?)
Comment: This is essentially checking the cyclotomic polynomial is irreducible. For a polynomial of such low degree you can write a factorization and solve for the coefficients.
Comment: Also it may simplify things to look at $\mathbb Z[X]/(X^5-1)$ as sort of a mediating step...
Comment: What is the definition of $f$?
Comment: @ajotatxe: I guess it is the evaluation map at $X:=\exp(2i\pi/5)$.
Comment: @მამუკაჯიბლაძე Not it doesn't.  A postiori this is $\mathbb{Z} \times \mathbb{Z}[e^{2\pi i/5}]$ which is just more complicated.
Comment: @FanZheng This is useless advice.  In the field case this allows us to say that the kernel must contain a prime ideal, and therefore it contains a maximal ideal, so it must be the maximal ideal.  But it implies nothing here when working over the integers, without a further argument:
Comment: @HariRau-Murthy I had in mind separating two different issues here: (1) universally adding a fifth root of 1 and (2) excluding 1 which itself happens to be a solution of $X^5=1$. Both separately are more easily understood than figuring out at once why $X^4+...+X+1$ is needed, no?
Comment: @მამუკაჯიბლაძე But 'figuring out why $X^4+\ldots+X+1$ is needed' isn't OP's trouble. It's pretty self-evident the connection between the two; OP's question is specifically showing that _every_ element of the evaluation map's kernel is in the ideal, and your suggestion doesn't do anything to help with that.
Comment: @StevenStadnicki Oh I see my mistake now, thanks
Comment: The main point is Gauss's lemma.  See my answer.
Comment: Almost by definition $\varphi : \mathbb{Z}[X]/(f) \to\mathbb{Z}[\alpha],\varphi(P) = P(\alpha)$ is an isomorphism of (commutative) rings whenever $f \in \mathbb{Z}[X]$ is the minimal polynomial of $\alpha$.
Comment: @HariRau-Murthy This is exactly what I mean, but I intend "essentially" in the sense of mathoverflow, without noting that this question has been migrated, in which case I would have said more.
Answer: $$f:\Bbb{Z}[X]\to\Bbb{Z}\left[{e^{2\pi i\over 5}}\right]\\X\to e^{2\pi i\over 5}$$
$f$ is ring homomorphism,
$$\Bbb{Z}[X]/\langle p(x)\rangle\simeq \Bbb{Z}\left[e^{2\pi i/5}\right]$$ where $p(x)$ monic irreducible polynomial and have root $e^{2\pi i/5}$
we have $p(x)=x^4+x^3+x^3+x^2+x+1$
Comment: And assume that $q(X) \in \mathbb{Z}[X]$ is the minimal polynomial of $e^{2i \pi / 5}$. Then $\mathbb{Z}[e^{2i \pi / 5}] \simeq \mathbb{Z}[X]/(q)$, but  $\sigma(e^{2i \pi / 5}) = e^{2i \pi k / 5}$, $k \in 1 \ldots 4$ is a ring isomorphism $\mathbb{Z}[e^{2i \pi / 5}]$ to itself, therefore $\sigma(0) = \sigma(q(e^{2i \pi / 5})) = q(e^{k 2i \pi / 5})$ i.e. $e^{k 2i \pi / 5}$ is a root of $q(X)$ and $p$ divides $q$.
Answer: $\newcommand{\Z}{\mathbb{Z}}$
$\newcommand{\Q}{\mathbb{Q}}$
$\newcommand{\cont}{\operatorname{cont}}$
$\newcommand{\Ker}{\operatorname{Ker}}$
Let $\phi(x)=x^4+..1$ and let $\Ker$ be the kernel of $\Z[x] \xrightarrow{evaluation} \Z[e^{2 \pi i/4}]$
Fact(see my comment above): The substitution map induces an iso $\Q[x]/(\phi(x)) \cong \Q[e^{2\pi i/5}]$.
Lemma: If $f \in \Ker$,$f$ has content 1, $\Rightarrow$ $f$ is in $(\phi) \in \Z[x]$.
Proof:
Now let $f \in \Z[x]$ satisfy $f(e^{2 \pi i/5})=0$ and also be of content 1.  Then $f =\phi h$ for some $h \in \Q[x]$.   Write $c h(x)=H(x)$ where $H(x)$ has content 1, and $c \in \Z$. Then $c=c \cont(f)=\cont(\phi)\cont(H)=1\cdot 1$. QED.
Now let $f \in Ker$ be arbitrary.  Then $f=\cont(f)  \cdot F$ where $F$ has content $1$.  $F$ is in $(\phi) \subset \Z[x]$ by the lemma, so $f$ is too.


Exchange 2019 Database Permissions

Question: I have an Exchange 2019 server which is running fine but ideally I would like to run offline defrag on an archive database that is now way bigger than it needs to be after removing a mailbox which, due to an errant import, copied many times more data to the archive than actually existed in the mailbox.
Name                        DatabaseSize                    AvailableNewMailboxSpace
----                        ------------                    ------------------------
Archives                    50.13 GB (53,821,308,928 bytes) 49.8 GB (53,472,526,336 bytes)

Problem is, the databases are not accessible (Administrator gets a permissions error even trying to browse to them), and I'd rather not mess with permissions on Exchange folders unless I have no choice - or following Microsoft documented procedures.
What's the correct process these days to do any sort of recovery/maintenance directly on the database files when Exchange is by default set up to only allow access to itself? Is eseutil even supported anymore or do they not recommend touching the edb files at all?
Answer:
the databases are not accessible Administrator gets a permissions error even trying to browse to them

When and where did you encounter this permission issue? When you run cmdlets which is related with database(e.g. Get-MailboxDatabase, Dismount-Database) or in other scenarios?
Make sure your current account has the permission to manage database: Mailbox database permissions

What's the correct process these days to do any sort of
recovery/maintenance directly on the database files when Exchange is
by default set up to only allow access to itself? Is eseutil even
supported anymore or do they not recommend touching the edb files at
all?

As far as I know, you could use eseutil tool to check the header of your corrupted database and repair your database when the State in the header shows "Dirty Shutdown". More details about how to use ESEUTIL to repair your database: Repair your Database with ESEUTIL
Besides, if you want to shrink the size of your databases, the following actions are recommended rather than offline defragmentation of the database via ESEUTIL:

Create a new database and associated database copies.

Move all mailboxes to the new database.

Delete the original database and its associated database copies.

The following related blog is for your reference: How to reclaim the whitespace
Edit: Location to modify permissions of database folders:
Comment: I'm doing all this as `administrator`. Trying to browse via explorer to `D:\Exchange Server\V15\Mailbox` just gives "You don't currently have permission to access this folder". All eseutil commands give permissions error if I try to provide the full EDB path. All Exchange Shell tools work fine (`Get-MailboxDatabase` etc)
Comment: Looks like I may be better off just moving to a new database
Comment: >> **"You don't currently have permission to access this folder"** Is it a local account? By default, the account **administrator** is a member of the group **Administrators**. Maybe you could view and modify the permissions of your current account and database folders? I added a screenshot of the location which to modify the permission, see if there is any difference after modifying/adding permissions for your administrator account.
Comment: I don't have permission to view security details on the folder without pressing the "Continue" button, which according to Microsoft `a background process will change the permissions on the folder, and on all its subfolders and files, to grant your user account access to them`. As mentioned previously I'd rather not cause any sort of change on the permissions unless it's a documented procedure, as generally, forcing permissions on critical Microsoft folders is a recipe for breaking things. I've broken folder redirection in the past due to it noticing unsupported permissions on the folders.
Comment: I went with the new database, although to further complicate things, it seems deleting a database from EAC doesn't actually remove the files - it tells you to remove them manually. Fortunately it seems that a simple `rmdir /s {DatabaseFolderPath}` works, even through you can't actually look in that folder
Comment: Has your disk space been shrinked after you migrated to a new database and removed the old db files?
Comment: Yes, the disk space has been reclaimed
Comment: If there is any similar issue, feel free to post it. If everything works well, you could mark the best answer to finish this thread. Have a good day :)
Answer: As Ivan_Wang suggested all the points, but There are some prerequisites before using eseutil:

Make a copy of your database before using eseutil.

Verify that you have sufficient space like equivalent of 20% of the database size.

Run Eseutil/P mode.

Run Eseutil /D mode.

Run Isinteg in -fix -test alltests mode.

Refer this: https://techcommunity.microsoft.com/t5/exchange-team-blog/repairing-exchange-databases-with-eseutil-when-and-how/ba-p/610276
https://community.spiceworks.com/how_to/168508-how-to-repair-exchange-databases-with-eseutil-when-and-how

Exchange 2019 Database Permissions


If X is second-countable, then X is Lindelöf space.

Question: Suppose that $X$ has countable basis, then every open covering of $X$ contains a countable subcollection covering $X$.
Proof
{$U_i;i\in I$} is open cover for ($X,\tau$) and $B$ = {$V_n;n\in N$} is countable base for topology $\tau$.We have that $X=\cup_i U_i$.For every point $x$ in $X$ let's choose any $U_i$ s.t. $x \in U_i$.Denote that $U_i$ as $U_x$.There exists $V_x \in B$ s.t. $x\in V_x\subset U_x$.Collection of $V_x$ is countable.For every $V_x$ choose $U_x$ s.t. $V_x\subset U_x$.Because $X=\cup_xV_x$ follows that $X=\cup U_x$ and number of $U_x$-s are countable.
I understood proof only last part I can't understand.Why we need that number of $U_x$ to be countable?
We have already open cover for $X$ and found {$V_x$} which is countable subcollection covering $X$.
Comment: My answer in the duplicate shows how we use (only) countable choice instead of full choice as in your proof. The basic $V_x$ are not the subcover, but you need to pick supersets from the original cover you start with.
Answer: {$U_i;i\in I$} is open cover for ($X,\tau$) and $B$ = {$V_n;n\in N$} is countable base for topology $\tau$.We have that $X=\cup_i U_i$.For every point $x$ in $X$ let's choose any $U_i$ s.t. $x \in U_i$.Denote that $U_i$ as $U_x$.There exists $V_x \in B$ s.t. $x\in V_x\subset U_x$.
Now as these $\{V_{x}\}$ which correspond to the $U_{x}$'s is a subcollection of $B$. Hence is countable as a subset of countable set is countable. Now it's just a matter of indexing. Explicitly we were looking at
$U_{0}=\{U_{x}\in \{U_{i}\}_{i\in I} : x\in V_{x}\subset U_{x}\}$. correspondingly we have $B_{0}=\{V_{x}: V_{x}\subset U_{x}\}$. These sets $B_{0}$ and $U_{0}$ are in bijection and $B_{0}$ being a subset of countable set is countable.
Write out all such $V_{x}$'s as a sequence say $\{V_{1},V_{2},.....\}$. Correspondingly we have $\{U_{1},U_{2},....\}$.
Thus $\{U_{k}\}_{k=1}^{\infty}$ is a countable subcover of $\{U_{i}\}_{i\in I}$
Comment: You have confused the definition of subcovers. It is not asked that whether we can find a countable subcover by basis elements.  We need a countable subcover of $U_{i}$'s that is we need a countable subcollection of $U_{i}$. Recall what we do to prove compactness, we take an arbitrary cover $U_{\alpha}$ and show there exists $U_{\alpha_{1}},U_{\alpha_{2}},...U_{\alpha_{n}}$ such that they cover $X$. I cannot just take another basis and say that they do so. That would prove absolutely nothing
Comment: When you are asked to find a subcollection of some collection of sets you necessarily have to form that subcollection by members of that original collection itself.
Comment: But {$V_x$} is also countable subcover of $U_i,i \in I$.Why we need another $\{U_{k}\}_{k=1}^{\infty}$?
Comment: It now makes sense,thank you!


How to create a new variable with values from different variables if another variable equals a set value in R?

Question: I have a complicated question that I will try to simplify by simplifying my dataset. Say I have 5 variables:
df$Id <- c(1:12)
df$Date <- c(NA,NA,a,a,b,NA,NA,b,c,c,b,a)
df$va <- c(1.1, 1.4, 2.5, ...)     #12 randoms values
df$vb <- c(5.9, 2.3, 4.7, ...)     #12 other random values
df$vc <- c(3.0, 3.3, 3.7, ...)     #12 more random values

Then I want to create a new variable that takes the value from va, vb, or vc if the date is equal to a, b, or c. I had tried a nested if-else, which did not work. I also tried:
df$new[df$date=='a' & !is.na(df$date)] <- df$va
df$new[df$date=='b' & !is.na(df$date)] <- df$vb
df$new[df$date=='c' & !is.na(df$date)] <- df$vc

This correctly left NA's in the new variable where Date=NA, however the values provided were not from va, vb, or vc, but some other value altogether. How can I get df$new to equal va if the date is 'a', vb if the date is 'b', and vc if the date is 'c'?
Comment: You want the `ifelse` function.
Comment: possible duplicate of [How to create a new variable with values from different variables if another variable equals a set value in R?](http://stackoverflow.com/questions/30113308/how-to-create-a-new-variable-with-values-from-different-variables-if-another-var)
Answer: You want the ifelse function, which is a vectorized conditional:
 > x <- c(1, 1, 0, 0, 1)
 > y <- c(1, 2, 3, 4, 5)
 > z <- c(6, 7, 8, 9, 10)
 > ifelse(x == 1, y, z)
 [1] 1 2 8 9 5

You will have to nest calls to this function, like this:
> x_1 <- c(1, 1, 0, 0, 1)
> x_2 <- c(1, 1, 1, 0, 1)
> y_1 <- c(1, 2, 3, 4, 5)
> y_2 <- c(6, 7, 8, 9, 10)
> z <- c(0, 0, 0, 0, 0)
> ifelse(x_1 == 1, y_1,
+   ifelse(x_2 == 1, y_2, z)
+ )
[1] 1 2 8 0 5

Your second attempt would succeed if you made the following modification:
df$new[df$date=='a' & !is.na(df$date)] <- df$va[df$date=='a' & !is.na(df$date)]

To avoid the new variable becoming a list rather than a numeric variable, use %in% in place of ==:
df$new[df$date %in% 'a' & !is.na(df$date)] <- df$va[df$date  %in% 'a' & !is.na(df$date)]

Comment: Thank you Matthew. I have not tried the ifelse that you suggested, though that appears it would work. After posting, I had someone here tell me the problem was that I did not put the indexing on both sides, which I did try and that worked.


QML Text sometimes skips rendering some characters

Question: I have an application where I display the time on the screen. It works well except very rarely it sometimes does not render the time fully and skips rendering a number. For example if time is "11:07", it would render "11:0 " or "1 :07". I know it's a rendering problem because it fixes itself when the time changes and I can't recreate it by force setting the same time. Also I have the time in another screen in much smaller font, and I never see this issue there. I suspect it's something to do with rendering text in a large fontSize that causes this problem.
I tried creating the duplicate of my time text and using TextMetrics for both time text elements and compare their widths. If their widths are different, I assume that it did not render fully. I don't think this would actually work tho since it seems like the width of the elements would be the same, even if they don't render fully. I looked into SafeText but that does not work for my constraints. I am using NativeRendering since my font size is big (> 200px). Here is a MRE:
import QtQuick 2.15
import QtQuick.Window 2.2
import QtQuick.Controls 2.15

Window {

    width: 1024
    height: 600
    visible: true
    property string time: Qt.formatTime(new Date(),"hh:mm")

    onTimeChanged: {
        if(timeText.width !== timeTextDuplicate.width || timeMetric.width !== timeMetricDuplicate.width) {
            console.log("They are not the same")
            // redraw time
            time = ""
            time = Qt.formatTime(new Date(),"hh:mm")
        }
    }

    Rectangle {
        id: root
        anchors.fill: parent
        color: "black"

        Text {
            id: timeText
            anchors.centerIn: parent
            font.pixelSize: 200
            color: "white"
            text: time
        }

        TextMetrics {
            id: timeMetric
            text: timeText.text
            font: timeText.font
        }

        Text {
            id: timeTextDuplicate
            font: timeText.font
            text: timeText.text
            visible: false
        }

        TextMetrics {
            id: timeMetricDuplicate
            text: timeTextDuplicate.text
            font: timeTextDuplicate.font
        }

        Timer {
            id: timer
            interval: 60000
            repeat: true
            running: true
            onTriggered: time = Qt.formatTime(new Date(),"hh:mm")
        }
    }
}

This is the output I get after setting QSG_RENDERER_DEBUG=render
Renderer::render() QSGAbstractRenderer(0x7f52702a63d0) "rebuild: full"
Rendering:
 -> Opaque: 1 nodes in 1 batches...
 -> Alpha: 6 nodes in 3 batches...
 - 0x7f52702be8a0 [  upload] [noclip] [opaque] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0
 - 0x7f52702be710 [  upload] [noclip] [ alpha] [  merged]  Nodes:    4  Vertices:    56  Indices:    84  root: 0x0 opacity: 1
 - 0x7f52702be240 [  upload] [noclip] [ alpha] [unmerged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0
 - 0x7f52702bdd70 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0 opacity: 1
 -> times: build: 0, prepare(opaque/alpha): 0/0, sorting: 0, upload(opaque/alpha): 0/0, render: 0
Renderer::render() QSGAbstractRenderer(0x7f5270006190) "rebuild: full"
Rendering:
 -> Opaque: 2 nodes in 1 batches...
 -> Alpha: 19 nodes in 17 batches...
 - 0x7f52700d50a0 [  upload] [noclip] [opaque] [  merged]  Nodes:    2  Vertices:     8  Indices:    12  root: 0x0
 - 0x7f52700d18a0 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0 opacity: 0.2
 - 0x7f52702c5ad0 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:   152  Indices:   232  root: 0x0 opacity: 0.2
 - 0x7f52702c59e0 [  upload] [noclip] [ alpha] [unmerged]  Nodes:    2  Vertices:   184  Indices:   280  root: 0x0
 - 0x7f52702c62c0 [  upload] [noclip] [ alpha] [unmerged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0
 - 0x7f52702fdc90 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:    32  Indices:    48  root: 0x0 opacity: 1
 - 0x7f527030db10 [  upload] [noclip] [ alpha] [unmerged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0
 - 0x7f52702c6040 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:    96  Indices:   144  root: 0x0 opacity: 1
 - 0x7f52702c5dc0 [  upload] [noclip] [ alpha] [unmerged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0
 - 0x7f52700d5360 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:    84  Indices:   126  root: 0x0 opacity: 1
 - 0x7f52700c8150 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0 opacity: 1
 - 0x7f52702f0730 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0 opacity: 1
 - 0x7f52702c0ce0 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:    16  Indices:    24  root: 0x0 opacity: 1
 - 0x7f52702c5f00 [  upload] [noclip] [ alpha] [  merged]  Nodes:    2  Vertices:   184  Indices:   284  root: 0x0 opacity: 1
 - 0x7f52702c5cb0 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0 opacity: 1
 - 0x7f52702c5bc0 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     8  Indices:    12  root: 0x0 opacity: 1
 - 0x7f52702c5800 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:     4  Indices:     6  root: 0x0 opacity: 1
 - 0x7f52702c58f0 [  upload] [noclip] [ alpha] [  merged]  Nodes:    1  Vertices:    48  Indices:    72  root: 0x0 opacity: 1
 -> times: build: 0, prepare(opaque/alpha): 0/0, sorting: 0, upload(opaque/alpha): 0/0, render: 0

I understand this could be a problem with the graphics card or QML itself, but is there anything I could do to detect that this has happened? Thanks
Answer: I use TextMetrics slightly differently. I built a BigText component that chooses the largest value for font.pixelSize so that your text will fit but will not exceed the bounding rectangle. It does this by:

Looking at the width and height of the bounding rectangle
Looking at the TextMetrics width and height for a "small" pixel size
Calculate a scale factor to multiply the "small" pixel size so that the text will fit nicely in the bounding rectangle

The other point I would like to make is in your code, you set TextMetrics font as follows:
        TextMetrics { // ...
            font: timeText.font
        }

I have found this can screw things up as you're no longer using the original font that came with TextMetrics. I have found it safer to copy the font properties you need, e.g.
        TextMetrics { // ...
            font.family: timeText.font.family
        }

To see these concepts in in action, I changed your application by (1) increasing the frequency of your timer from 1 minute to 1 second. Change the time format from "hh:mm" to "hh:mm:ss".
Whilst running this app, try resizing the window and note the text font dynamically changes.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
    id: page
    property double time: Date.now()
    //property string timeString: Qt.formatDateTime(new Date(time), "hh:mm")
    property string timeString: Qt.formatDateTime(new Date(time), "hh:mm:ss")
    ColumnLayout {
        anchors.centerIn: parent
        BigText {
            backgroundColor: "black"
            color: "white"
            Layout.alignment: Qt.AlignHCenter
            Layout.preferredWidth: page.width / 2
            Layout.preferredHeight: page.height / 2
            text: timeString
        }
        RowLayout {
            Layout.alignment: Qt.AlignHCenter
            Button {
                Layout.preferredWidth: height
                text: "-"
                //onClicked: slider.value -= 60000
                onClicked: slider.value -= 1000
            }
            Slider {
                id: slider
                Layout.fillWidth: true
                from: hhmm(0, 0, 0)
                to: hhmm(23, 59, 59)
                value: Date.now()
                function hhmm(hh, mm, ss) {
                    let d = new Date();
                    d.setHours(hh);
                    d.setMinutes(mm);
                    d.setSeconds(ss);
                    return d.getTime();
                }
                onValueChanged: {
                    autoButton.checked = false;
                    time = value;
                }
            }
            Button {
                Layout.preferredWidth: height
                text: "+"
                //onClicked: slider.value += 60000
                onClicked: slider.value += 1000
            }
        }
        Button {
            id: autoButton
            Layout.alignment: Qt.AlignHCenter
            text: qsTr("Auto")
            checkable: true
            Component.onCompleted: checked = true
        }
    }
    Timer {
        id: timer
        interval: 1000
        repeat: true
        running: autoButton.checked
        onTriggered: time = Date.now()
    }
}

// BigText.qml
import QtQuick
import QtQuick.Controls
Text {
    id: bigText
    width: 200
    height: 100
    color: "black"
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
    property color backgroundColor: "white"
    Rectangle {
        anchors.fill: parent
        color: backgroundColor
        z: -1
    }
    property TextMetrics tm: TextMetrics {
        font.pixelSize: 10
        font.family: bigText.font.family
        text: bigText.text
    }
    font.pixelSize: tm.font.pixelSize * Math.min(bigText.width / tm.width, bigText.height / tm.height) * 0.9
}

You can Try it Online!
Comment: Right now, it's hard for you to repro because (1) the changes occur on a 60 minute Timer, (2) the text is also set by the Timer. To make it easier to reproduce, you should do a "functional test" by swapping out the Timer for UI/UX control such as ComboBox, Slider, Spinner, or Tumbler. That way, you can manufacture the problematic test cases on demand. I've updated the answer to show how you may swap out the Timer for such as unit test.
Comment: Thanks for the answer! Unless I misunderstood your solution, I think my question is a little different. My problem is not making the text fit on the screen or to avoid clipping, my problem is specifically with rendering. I sometimes see time as "11: 7" when it's "11:07". I know it's a rendering problem because it fixes itself when the time changes and I can't recreate it by force setting the same time. Also I have the time in another screen in much smaller font, and I never see this issue there.
Comment: @EvanKrause I see, are you on Windows? Are you on Qt5 or Qt6? Perhaps it's your OpenGL support and your graphics card driver that's an issue. You can try updating your graphics driver and/or changing your rendering engine (e.g. between ANGLE to OpenGL). See https://stackoverflow.com/questions/41021681/qt-how-to-detect-which-version-of-opengl-is-being-used
Comment: In particular look at explorative troubleshooting by setting the `QT_OPENGL` environment variable with values `desktop`, `angle`, or `software` prior to running your app.
Comment: I'm on Linux using Qt5.15.0 with OpenGL 4.6. I can try changing the rendering engine, but since this happens so rarely, it might take weeks or longer to even notice a difference. How would I know that the problem has been solved? Is there a way to detect rendering issues? I have render logging turned on but so far I haven't seen anything out of the usual.
Comment: That's a good suggestion, I'll try that and see if I can repro it more often. Thanks!


Bootstrap navbar dropdown menu controle do foco depois do clique

Question: Situação

Tenho um navbar no meu site, e nele eu possuo diversos menus dropdown / megamenus.
Preciso que quando seja clicado neste dropdown, o usuário tenha a opção de "rolar" a página para cima e para baixo com as setas direcionais do teclado.
Com o scroll do mouse isto já funciona
Mas o teclado não... mesmo se setar o foco (utilizando o .focus() do jquery) em algum elemento que esteja fora do navbar.

JSFiddle está aqui, redimencionem a tela se o dropdown não aparecer.
Depois tente apertar para cima e para baixo no teclado, neste caso não irá funcionar (a tela não irá para baixo nem para cima)... só funciona com o scroll do mouse, e eu precisaria que isso funcionasse com o teclado também
Answer: Daniel, aqui fica uma sugestão: http://jsfiddle.net/Lqdxf/
$('.navbar-collapse').keyup(fazerScroll);

function fazerScroll(event) {
    if (!$('.navbar-collapse').is(':visible')) return;
    var navBar = document.querySelector('.navbar-collapse');
    var scrollAtual = navBar.scrollTop;

    var incremento = event.keyCode == 40 ? 100 : event.keyCode == 38 ? -100 : 0;
    if (!incremento) return;
    $(navBar).stop().animate({
        scrollTop: scrollAtual + incremento
    }, 500);
}

Esse código chama a função fazerScroll() cada vez que uma tecla é pressada dentro da nav-bar. Quando a função abre verifica se o dropdown está visivel, senão pára.
Depois mede a posicao atual to scroll e incrementa 100px no caso de a tecla carregada ser cima e -100px no caso de ser baixo.
Antes de fazer a animacao para a posicao final, verifica se existe incremento para evitar correr a funcao .animate(). Note que usei o .stop() para permitir que o animate volte a correr noutra direcao caso carregue nas teclas rápido, senao ele ia acumular instrucoes e ter um comportamento extranho
Answer: Não sei se é isso que vc está precisando, mas vc pode criar um bind do evento keyup e verificar se o usuário pressionou as setas para cima ou para baixo e fazer a rolagem da tela:

$(document).keyup(function(event) {
  if(event.keyCode == 38) { // codigo da seta pra cima
    // faça a rolagem pra cima
  } else if(event.keyCode == 40) { //codigo da seta pra baixo
    // faça a rolagem pra baixo
  }
});

Para fazer a rolagem da tela para algum elemento você pode usar o método scrollTop do jquery:

$('html, body').animate({
    scrollTop: ($('seletor-do-elemento').offset().top)
},500);

Comment: Obrigado pela resposta, mas isto não seria bem o que estou precisando. O problema em si é o seguinte... Tente abrir o JSFiddle, e em seguida clique no menu dropdown, com ele aberto, tente apertar para cima e para baixo no teclado, neste caso, não irá funcionar (a tela não irá para baixo nem para cima)... só funciona com o scroll do mouse, e eu precisaria que isso funcionasse com o teclado também.
Answer: Então pessoal, acabei encontrando uma resposta.
Clique aqui para ver o jsfiddle
Acabei captando o evento de onclick do menu.
Evito a propagação deste evento.
E controlo a abertura e o fechamento do menu na mão.
Para isto, eu tive que retirar o atributo data-toggle do menu.
Obrigado pela ajuda.


How can I expand the width of the wheel?

Question: I have been trying for hours to change the width of the wheel and items, but I cant figure out how to https://jsfiddle.net/ywm3zbc4/105/
I want to change the wheel width to 600px and still use the function to choose where the wheel should land
    .wheel {
      width: 600px;
    }

    var wheel = new SpinWheel(20);

Without it breaking compleatly, when running it after changing the width it skips over and doesnt land on "20"
Comment: Alright, I edited the post.
Comment: what width do you want? 470? what do you mean breaking it completely it seems to work please explain yourself more.
Comment: If you edit the width of the wheel and then run the function to land on e.x 20
Example:    var wheel = new SpinWheel(20);
 it wont land on 20 it breaks the function
http://prntscr.com/lep0fe
Comment: well it does for me? the width shouldnt affect it as its centered, did you write this code or get it from somewhere else?
Comment: If you change the width of the wheel to example 600px

And then change var wheel = new SpinWheel(resultID);
To var wheel = new SpinWheel(20);

It should land on 20 but doesnt becouse the width was increased
http://prntscr.com/lep25c
Comment: so you want it responsive because it seems in your post you just want the width to be 470? please edit your post to be what you want, what you expected, and what acutally happened, and reasons why you think it happened or reasons why you know it wont work.
Answer: As Inside wheel-wrapper class you have (39 wheel-items) wheel-item. you need to change width at both places wheel-wrapper and wheel-item. you need to divide wheel-wrapper by wheel-item you supposed to want. for example, I have took 2925px width of wheel-wrapper and you had 39 items. As per this, wheel-item's width 75px.
Note: you can change it as per your requirements.
Changes I have made:
.wheel {
  width: 470px;
  height: 50px;
  padding: 10px 9px;
  margin: 0 auto;
  overflow: hidden;
  &-wrapper {
    width: 2925px;   //changed
  }
  &-item {
    float: left;
    width: 75px;    //changed
    height: 30px;
    color: white;
    text-align: center;
    p {
      line-height: 30px;
      margin: 0;
    }
  }

Test link
Comment: Scroll down on the script and change
    var wheel = new SpinWheel(resultId);
to var wheel = new SpinWheel(20);          Even though it should land on 20 it doesnt


a matrix of rank $r$ satisfies a polynomial of degree $r+1$.

Question: Let $M$ be an $n\times n$ matrix with coefficients in $\mathbb C$. Suppose $M$ has rank $r$ with $r<n$. Prove there is a polynomial $P(x)$ with degree $r+1$ and coefficients in $\mathbb C$ such that $P(M)$ is the zero matrix.
I think this has to do with the minimal/characteristic polynomials, although I have not yet seen this in school. I would appreciate a comprehensive solution, hopefully referencing the theorems as they are used.
Comment: Do you know Jordan canonical form?
Comment: no, I do not know Jordan canonical  I'm supposed to see that this semester.
Answer: Small variation of the answer of loup blanc that does not mention minimal polynomials, and produces an actual annihilating polynmial of degree $r+1$. Note that is is irrelevant that the vector space is over$~\Bbb C$.
The image space $W$ of $M$ (or column space if you prefer) has dimension $r$ by definition of the rank. The characteristic polynomial $Q$ of the endomorphism of$~W$ obtained by restriction of $M$ has degree$~r$ (one can compute this polynomial by expressing the restriction as an $r\times r$ matrix on some basis of the image). Then by Cayley-Hamilton, the restriction of $Q[M]$ to $W$ is zero, i.e., $Q[M]$ vanishes on$~W$. Since $W$ is the image of$~M$, this implies that $(QX)[M]=Q[M]\cdot M=0$, and $QX$ is our annihilating polynmial of degree $r+1$.
Answer: Since $\dim(\ker(M))=n-r$, there is an invertible matrix $P$ s.t. $P^{-1}MP=\begin{pmatrix}0_{n-r}&A\\0&B_r\end{pmatrix}$. Let $P$ be the minimal polynomial of $B_r$; its degree is $\leq r$. Finally, the minimal polynomial of $M$ divides $xP(x)$ and we are done.
Comment: Why the minimal polynomial of M divides xp(x) ? I can't understand why $P^{-1}MP$ is a root of xp(x) ?
Comment: @ user371231 , you downvote my post, that you did not understand, before having the answer to your question. Incredible...
Comment: Sorry for that..now I understand my misunderstanding.I will upvote it immediately it works.


Fancybox module error messages

Question: I enabled the fancybox module, but since doing so am getting the following error messages:
<code>Notice: Undefined index: options in _fancybox_filter_settings() (line 559 of /home/mysite/public_html/sites/all/modules/fancybox/fancybox.module).
Warning: Invalid argument supplied for foreach() in _fancybox_filter_settings() (line 559 of /home/mysite/public_html/sites/all/modules/fancybox/fancybox.module).
</code>
Any advice as to how to fix them?
Comment: which version are you using?
Answer: I guess you have a solution available in the following bug report filed at http://drupal.org/node/1904006
You have two possible options available.
1. There is a patch available in that post, use that.
2. Download development release, which already has that path applied in it.

Fancybox module error messages


Gradle Build Failure

Question: My project compiles and executes well on debug mode but when i try to generate a signed apk, errors arise. This appears on the message log:
:app:proguardRelease
Warning:android.support.v4.app.DialogFragment: can't find referenced class android.support.v4.app.DialogFragment$DialogStyle
Warning:android.support.v4.app.FragmentTransaction: can't find referenced class android.support.v4.app.FragmentTransaction$Transit
Warning:android.support.v4.view.ViewCompat: can't find referenced class android.support.v4.view.ViewCompat$ResolvedLayoutDirectionMode
Warning:android.support.v4.view.ViewCompat: can't find referenced class android.support.v4.view.ViewCompat$LayoutDirectionMode
Warning:android.support.v4.view.ViewCompat: can't find referenced class android.support.v4.view.ViewCompat$LayerType
Warning:android.support.v4.view.ViewCompat: can't find referenced class android.support.v4.view.ViewCompat$AccessibilityLiveRegion
Warning:android.support.v4.view.ViewCompat: can't find referenced class android.support.v4.view.ViewCompat$ImportantForAccessibility
Warning:android.support.v4.view.ViewCompat: can't find referenced class android.support.v4.view.ViewCompat$OverScroll
Warning:android.support.v4.widget.DrawerLayout: can't find referenced class android.support.v4.widget.DrawerLayout$EdgeGravity
Warning:android.support.v4.widget.DrawerLayout: can't find referenced class android.support.v4.widget.DrawerLayout$LockMode
Warning:android.support.v4.widget.DrawerLayout: can't find referenced class android.support.v4.widget.DrawerLayout$State
Warning:there were 11 unresolved references to classes or interfaces.
         You may need to add missing library jars or update their versions.
         If your code works fine without the missing classes, you can suppress
         the warnings with '-dontwarn' options.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)
Exception while processing task
java.io.IOException: Please correct the above warnings first.
    at proguard.Initializer.execute(Initializer.java:473)
    at proguard.ProGuard.initialize(ProGuard.java:233)
    at proguard.ProGuard.execute(ProGuard.java:98)
    at proguard.gradle.ProGuardTask.proguard(ProGuardTask.java:1074)
    at com.android.build.gradle.tasks.AndroidProGuardTask.doMinification(AndroidProGuardTask.java:139)
    at com.android.build.gradle.tasks.AndroidProGuardTask$1.run(AndroidProGuardTask.java:115)
    at com.android.builder.tasks.Job.runTask(Job.java:48)
    at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
    at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:227)
    at java.lang.Thread.run(Thread.java:745)
:app:dexRelease UP-TO-DATE
:app:crashlyticsStoreDeobsRelease
:app:crashlyticsUploadDeobsRelease
:app:validateExternalOverrideSigning
:app:packageRelease FAILED
Error:Execution failed for task ':app:packageRelease'.
> Unable to compute hash of /home/kombo/RAL/Mpasho/app/build/intermediates/classes-proguard/release/classes.jar

I have tried every possible way of remedying this by updating my build tools, using the latest gradle version, checking all the dependencies and the error still shows up.
I am pretty sure the v4 support library is present in the project since no errors arise in debug mode.
Answer: I also had this issue when upgrading everything that is built related to 23 (Android Libraries, SDK etc).
This proguard configuration fixed it for me:
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn com.google.android.gms.**
-dontwarn com.android.volley.toolbox.**

Source
Comment: Good find. This was it.
Comment: Worked for me too!! after 3 hrs of searching!! Thanks a lot sir!!
Comment: This is assuming people are using volley.
Comment: @Ahmed in your proguard configuration file
Comment: Not working for me: http://stackoverflow.com/questions/35804397/proguard-and-apache-legacy
Answer: Turns out I had omitted the getDefaultProguardFile('proguard-android.txt') line on the proguard files and was just using proguard-rules.pro
Comment: I had the same problem. Cleaning, clearing caches didn't resolve it.
When I looked higher in the build log, I noticed that proguard was spouting some warnings. I probably had 2 libraries that were sharing some code (duplicate classes..)

I removed one of the offending library and it fixed my proguard issue
--> look at your build output for proguard warnings/errors
Comment: @dangalg checkout my answer
Comment: so you are not using proguard at all mate. try to decompile you apk and see that you get the exact project files
Answer: added these two line in progaurd
-dontwarn android.net.http.AndroidHttpClient
-dontwarn com.google.android.gms.**

and it works..
It is related to library used in project.
Answer: The default ProGuard file already has a rule to ignore support library warnings. If you don't have it you can add to your file
-dontwarn android.support.**

but would be better to add the default one. See Proguard configuration@Android Developers
Comment: That only gets me as far as removing the warnings. But this error still persists, `Error:Execution failed for task ':app:packageRelease'.
> Unable to compute hash of /home/kombo/RAL/Mpasho/app/build/intermediates/classes-proguard/release/classes.jar`
Comment: This is very frustrating, I have tried almost everything and I can not fix it :$
Comment: Same problem... no solution.
Comment: Same problem, no solution yet
Answer: This also could happen due to errors/warnings related to included .jar files
Check in build output for proguard warnings/errors.
I had issue related to opencsv jar file. Hint by Lakedaemon in above comment helped me and its solved.
Answer: Try to look up in the whole error message. It may contain info that you include a library twice. This was the problem in my case and it was fixed after removing duplicated includes.
Answer: Try add this code in your proguard-rules.pro:
-ignorewarnings

It solved my problem.
Answer: I think your app build.gradle buildTypes > release > minifyEnabled is true
That cause you get this error message.
Avoid this error message, set buildTypes > release > minifyEnabled is false

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

Comment: This is not a solution is you need pro-guard enabled
Comment: Thanks! You saved my day

Gradle Build Failure


How to manage editing and publication of content

Question: The scenario is this:

Content is created or edited:

At that point, the content should be marked or moved to a state of "edited" If the content is new, it should not be published.
If it is an existing node, it the ORIGINAL version should REMAIN published until it is "approved".

Content is approved:

If the approved node is preexisting, the edited version replaces the old version.
Otherwise, it is new content and it is moved from not published to published.
I'm looking for suggestions on how to accomplish this. My hope was to use the module Workflow and integrate it with Triggers.
So far, I'm not seeing an obvious path to making this work as described above.
Answer: I think you're looking for the Workbench Moderation module.  From the project page:

Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.
Comment: I suspected that may be the route... Will Workbench allow a "Published" node to be edited, and upon edit, allow the original Published state to remain Published (publicly visible) - then upon "Approval" of the edited content, replace the old published content with the new approved content?  Thank you for the feedback!
Comment: Have a look at the first page of the [documentation](https://www.drupal.org/documentation/modules/workbench_moderation): `Once a node is published, its current revision is always the published version. Workbench Moderation changes this; it allows you to use an older revision of a node as the published version, while continuing to edit a newer draft.`
Comment: Oh and note that Workbench Moderation is an addon to Workbench, you'll need both modules I think.
Comment: That's exactly what I was thinking of. +1 Workbench Moderation module
Answer: You can also try the Revisioning module which describes itself:

... for the configuration of workflows to create, moderate and publish
  content revisions. You use it in scenario's like this:
Authors write content that prior to being made publicly visible must
  be reviewed (and possibly edited) by moderators. Once the moderators
  have published the content, authors should be prevented from modifying
  it while "live", but they should be able to submit new revisions to
  their moderators.


política de mesma origem como contornar

Question: Possuo um site em um certo domínio e dentro desse site um Iframe com domínio porta e host diferente, porém dentro desse Iframe eu desejo realizar um "document.getElementsByClassName('classe')[0].innerText" de uma classe de fora do Iframe, porém aparece o erro:

"VM2184:1 Uncaught TypeError: Cannot read property 'innerText' of
  undefined
      at :1:131"

Acredito que seja pelo fato de estar tentando ler um dado de fora do Iframe, pesquisei varias formas de solucionar mas até agora não achei uma resposta que me atendesse.
Código:

 $(document).ready(function teste() {
            var dados = window.document.getElementsByClassName('classe')[0].innerText
            if (dados != null) {
                document.getElementById('nome').value = dados;
                $.post("/WebAPI/api/funcao", { data: dados });
                reset();
            }
        });
Answer: Bom, isso acontece por que você está executando o script dentro da sua pagina principal! Então realmente não existe essa classe na sua pagina principal e sim no iframe, para acessar o as classes/id's dentro do iframe você precisa fazer isso:
document.getElementsByTagName("iframe")[0].ownerDocument.getElementsByTagName("html")[0].getElementsByClassName("exemplo")
Espero ter ajudado!!
Comment: faz sentido kk, muito obrigado esclareceu bastante as coisas aqui!
Comment: Existe um caminho reverso também? tipo eu to no Iframe executando um código para pegar um elemento da página principal?
Comment: Ao contrario não! Seria bem inseguro! Imagina você colocar um script na sua pagina que ferra com a index de quem colocar o iframe nela!
Comment: Se consegui responder com precisão, poderia marcar como correta? =D
Answer: Você não está tendo um problema de Política de "mesma origem", ainda.
Para tentar acessar o conteúdo do parent você pode utilizar algo como parent.document.getElementsByClassName('suaClasse')[0].innerText e aí sim ter um problema com o CORS pois não é possível realizar comunicação entre um iframe e outro domínio:porta.
Answer: Para quem está precisando pegar o elemento da página principal e passar para um Iframe de domínio diferente leia a resolução a seguir, após pesquisar milhares de sites chineses e turcos eu finalmente achei uma solução.
Na pagina que você vai enviar o elemento coloque o seguinte código

window.parent.frames[0].postMessage( tes, '*');

Na página que vai receber o elemento coloque o seguinte código

window.addEventListener("message", function(e){
 //faca qualquer coisa aqui como atribuir a uma variável e tal e usar depois, coloque o alert só para ver se o elemento estava chegando e sim ele chegou!
  alert(e.origin + "-" e.data);
},false);

Já deixo avisado que não sei se o método usado é seguro para evitar que outros sites peguem esse elemento que você está transferindo mas, está funcionando.

política de mesma origem como contornar


Webpack is not copying images to dist folder

Question: I'm starting with webpack, but I'm really new on this and I'm stuck right now.
My project copies my fonts correctly but not images. Now the only way I am able to make it work is by copying my images manually to the dist/img folder.
This is my config:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require('webpack');
var path = require("path");

module.exports = {
entry: './src/app.js',
output: {
    path: path.resolve(__dirname + '/dist'),
    filename: 'app.bundle.js'
    // publicPath:  '/dist',
},
module: {
    rules:[
        {
        test:/\.scss$/,
        use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: ["css-loader?sourceMap","resolve-url-loader","sass-loader?sourceMap"],
            // publicPath: '/dist'
            })
        },
        {
            test: /\.(woff2?|ttf|otf|eot|svg)$/,
            use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'fonts/'
                    }
                  }]
            // loader: 'file-loader?name=/fonts/[name].[ext]'
        },
        {
            test: /\.(jpg|png|gif)$/,
            use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'img/',
                        publicPath:'img/'
                    }
                  }]
        }
    ]
},
devServer: {
    contentBase: path.join(__dirname, "/dist"),
    compress: true,
    port: 8000,
    stats: "errors-only",
    open: true
},
plugins: [
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    new ExtractTextPlugin("styles.css"),
    new HtmlWebpackPlugin({
        title: 'Project',
        hash:true,
        template: './src/index.html'
    })
]
}

I've tried several configurations but no solution. I also searched here for any solution but without success.
Answer: If your images are only referenced in HTML files as  tags, webpack by default won't pick them up because it doesn't parse HTML. You have at least 2 choices:

Use CopyWebpackPlugin to copy the files to wherever you want, this at least removes the "manual" part you mention
Move your images references to styles, where webpack can pick them up via the scss loader you are using. For example
background-image: url("img/foo.png");

Comment: Ah ok thanks!
I´m trying now with CopyWebpackPlugin and it works great!
Comment: great! Please accept this answer if it is working for you.
Comment: new CopyPlugin([
            { from: './img/*', to: 'img', force: true},
          ])
Comment: i'm try to use your solution but i have problem
Comment: It works, but copy files without image optmizations
Answer: There is also option import image trough JavaScript.
import '../img/image.png';

Answer: I had this problem. I didn't know that the file-loader only copies the images if you run a build, and doesn't do anything while using webpack-dev-server. My solution was just:
$ npx webpack


Perl regex to extract groups of digits from string of dot-separated integers

Question: First off, I'm working with Perl 5.14.1.
I've been pulling my hair out over the following issue (NOTE: I absolutely suck at anything to do with regular expressions). I'm looking for a regular expression to extract only the numbers from strings such as the following:
E4.1
E6
e16
e6.7.3
E42.9

Basically, there's always an e (upper or lower case) followed by at least one group of digits. If there are multiple groups of digits, they are separated by a dot. What I want to do is to extract all groups of numbers into an array. For instance:
E4.1 -> ( 4, 1 )
E65 -> ( 65 )
e5.8.3 -> ( 5, 8, 3 )

where the stuff in parentheses is supposed to be the arrays of numbers I extracted from the strings.
What I got so far is
my @groupsOfNumbers = ( $inputString =~ /(\d+)((\.)\d+)*/g );

My reasoning here was, there's always at least one group of numbers (hence the first (\d+)), optionally followed by any number of dot-followed-by-digits groupings (hence the ((.)\d+)* part). Unfortunately this doesn't seem to work. For example, if I apply that regex to this input:
E4.3.1

the result is:
( "4", ".1", "." )
Please help!
Answer: You don't have to bother with dot matching, as you want only numbers,
my @groupsOfNumbers = $inputString =~ /(\d+)/g;

Comment: I would go with non regex solution https://eval.in/174459 Yes, plain looks/behaves like work of art. :)
Comment: Hi Flanker (love that plane)! ;-)

True, but I'd also like a minimal bit of validation, so that for instance the following string "e4_4_6_2" doesn't return any numbers at all.

EDIT: Well come to think of it, I can probably do without that. Your answer will do. Thanks!