Where can I find the form API reference?

Question: Form API Reference gives information about which properties to use for a form array, for Drupal 7.
Where can I see what properties I can use in buildForm(array $form, FormStateInterface $form_state), such as #type, #title, #required, and other possible properties?
Actually I'm using the Drupal 7 information in Drupal 8, and it works, but there should/must be an updated page, I guess.
Comment: https://api.drupal.org/api/drupal/elements/8.6.x
Comment: It's really hard to find this information because it's not presented in the same manner. Essentially all elements implement [ElementInterface::getInfo()](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21ElementInterface.php/function/ElementInterface%3A%3AgetInfo/8.6.x), and this is where that information is for each element. The api project on drupal.org really should implement a way to aggregate things like this.
Comment: https://api.drupal.org/api/drupal/elements/
Comment: @Kevin, I don't see the where in that page says the field can have entries like "#title", "#type" or "#required" etc. Where can I have this information? I've edited the question to be more clear.
Answer: Many of the form element properties are listed in the documentation for the FormElement class. The properties described there are:

#after_build
#ajax
#array_parents
#default_value
#description
#disabled
#element_validate
#field_prefix
#field_suffix
#input
#parents
#process
#processed
#required
#states
#title
#title_display
#tree
#value_callback

Form and render elements shows a list of the form and render elements implemented by Drupal core, with a link to the class implementing them.

It contains also the following sentences. (Emphasis is mine.)

Each form and render element type corresponds to an element plugin class; each of them either extends \Drupal\Core\Render\Element\RenderElement (render elements) or \Drupal\Core\Render\Element\FormElement (form elements). Usage and properties are documented on the individual classes, and the two base classes list common properties shared by all render elements and the form element subset, respectively.

There isn't a single page describing all the form element properties, but there is a page for each plugin class that implements a form element.
Comment: I've updated Drupal documentation here: https://www.drupal.org/docs/8/api/form-api/form-render-elements. Thank you.


Should we really have a Homework/Self-Study tag

Question: I'm coming from the discussions in the comments here.
I disagree that voting up that question (as I too did) implied having a consensus on a homework/self-study tag (as I, for example, did not).
So I would rather have this as an explicit discussion here. Here's just why I think these tags are not useful (but again, up voting this question does not imply - imo - that you agree with me, rather agreeing that this is a relevant issue):
Content wise
We cannot infer quality of questions from these tags. Almost all other "undergrad questions" could have been from their homework. Almost all questions from this guy are (i) copy paragraph from Mankiw that has question and answer (ii) say why his intuition gives him different results (iii) ask for the correct intuition. Does that make them homework questions? No, because it wasn't his homework. Self-study, perhaps. Does it make the content any better/worse compared to a homework question?
Where is the distinction?
All of us are trying to learn Economics. That's the process of dealing with questions that come to mind. Should we add self-study to all the questions now?
What if someone, as a homework exercise, has to answer an intuitive question similar to "Why do we call trade deficits so despite the importers paying the exporters in currency?" He then, trying to grasp the matter, asks this. Now, it is still a "homework question", but differently phrased. Should we tag anything that could be used to do homework?
tldr;
There is no special information in whether sth is homework or not, in order to warrantee such a tag. For these matters, we already are testing academic-graduate. Furthermore, any question can be a homework question (with good or bad effort to hide).
Comment: Mathematics.se recently [had this discussion](http://meta.math.stackexchange.com/questions/14981/homework-tag-should-be-deprecated-votings-over-you-wont-believe-what-won/16337#16337), which resulted in the (homework) tag being burninated and blacklisted on mathematics.se.
Answer: I think the only thing we buy with a homework tag is the hypothetical ability to have a lower standard for those types of questions if we should so desire.
I.e. "Well, s/he's clearly a student so I'll cut them some slack."
It may also serve as a signal to use more concise explanations, and simpler terms in formulating the response.
Otherwise, I agree it does little to effectively signal others on the site.
Answer: I think a homework tag is worthwhile having. It is useful because it quickly explains the intent of the questioner. A succinct, relatively technical answer with some explanation about the intuition will usually suffice.
I am not a huge fan of the self study tag because I don't think it adds much. A collection of questions tagged as self study would be very broad, covering essentially every aspect of economics. tagging something as homework provides at least some guide as to the level required.
Answer: I have just noticed that we have a self-study tag. I noticed because it was attached to a very low level question. I think this tag does more harm than good. To some people it will seem that low level or no effort questions are okay as the OP is a student. (Learning by not thinking about the problem?) The possible gain which would be requesting a specific level of answer can be attained by specifying the desired level in the question. In fact this is probably a clearer signal.
So I would say no, we should not have this tag.
Answer: I like the idea of a self-study tag to clarify the intention of the poster.  It is blatantly obvious to most of us when a person is trying to get someone to do his or her homework for them.  Having a self-study tag with clear rules about using this forum for getting homework or other self-study help would force new posters to edit their posts to show prior effort at solving the problem or have the post closed.  I like the approach Cross Validated uses for self-study questions (also copied below), which I believe is based on SO's policy.  I don't think there's a problem with trying to get self-study help here, just don't expect to get any help without showing effort.
I think the first step for such a tag would be to agree on the ground rules for self-study questions and the policies that the community would enforce, i.e. through flags.

About self-study
A routine question from a textbook, course, or test used for a class or self-study.
The following guidelines are for those who are asking and those who would answer self-study questions.
They are rooted in two principles:

It is okay to ask about homework.  Homework is included in this self-study tag. This site exists to help people learn and provide a standard repository for questions in statistics and machine learning, both simple and complex, and this includes helping students.
Providing an answer that doesn't help a student learn is not in the student's own best interest. Therefore you might choose to treat self-study questions differently than other questions.

Asking about self-study questions

Make a good faith attempt to solve the problem yourself first. If don't seem to be making a genuine attempt, your question might be voted down or closed.
Ask about specific problems you have encountered in your initial efforts. If you can't do that yet, try some more of your own work first or searching for more general help.
Be honest about the source of the question.  Do this by adding the self-study tag and mentioning whether it is for some class in the question text.
Be aware of school policy (if relevant). If your school has a policy regarding outside help on homework, make sure you are aware of it before you ask for/receive help here. If there are specific restrictions (for example, you can receive help, but not full solutions), include them in the question so that those providing assistance can keep you out of trouble.
Never use a solution you don't understand. It definitely won't help you later (after school, in later assignments, on tests, etc.) and it could be, at best, very embarrassing if you are asked to explain what you turned in.

Answering self-study questions

Try to provide explanations that will lead the asker in the correct direction. Genuine understanding is the real goal for students, but trying to provide that is seldom unappreciated for any question.
It's usually better not to provide a complete solution (or code sample) if you believe it would not help the student, using your best judgment. You can use pseudo-code and general descriptions first.  In the spirit of creating a resource, you may come back after a suitable amount of time and edit your response to include more details, if the question seems like such information will have lasting value.
Don't downvote others who answer coursework-related questions in good faith, even if they break these guidelines. It is a good idea to suggest editing the response in a comment.
Don't ridicule a student because they haven't yet learned something obvious or developed the good habits you'd expect from an expert. Do add a respectful comment or answer that points them towards best practices and better style.
Don't downvote a homework question that follows the guidelines and was asked in good faith. CV explicitly accepts homework questions that follow the guidelines. Consider making helpful suggestions for improving the question instead.
Don't edit a question to add the self-study tag. If there's any room for doubt at all, it's best to leave it as is. Instead, add a comment first requesting that the asker clarify the situation.

(Adapted from an SO post by Joe Coehoorn as suggested in a meta discussion)


Does Ruby Hash's keep a separate list of read values vs assigned values?

Question: This is related to Ruby hash default value behavior
But maybe the explanation there doesn't include this part: it seems that Ruby's Hash default value are separate whether you "read it", or see "what is set"?
One example is:
foo = Hash.new([])

foo[123].push("hi")

p foo       # => {}
p foo[123]  # => ["hi"]
p foo       # => {}

How is it that foo[123] has a value, but foo is all empty, is somewhat beyond my comprehension... the only way I can understand it is that Ruby Hash keeps a separate list for the "read" or "getter", while somehow the "internal" assigned value are different.
If one of Ruby's design principles is "to have the least amount of surprise to the programmers", then the foo is empty but foo[123] is something, is somewhat in this case, a surprise to me.
(I haven't seen that in other languages actually... if there is a case where another language has similar behavior, maybe it is easier to make a connection.)
Answer: Suppose `
h = Hash.new(:cat)
h[:a] = 1
h[:b] = 2
h #=> {:a=>1, :b=>2}

Now
h[:a] #=> 1
h[:b] #=> 2
h[:c] #=> :cat
h[:d] #=> :cat
h     #=> {:a=>1, :b=>2}

h = Hash.new(:cat) defines an empty hash h with a default value of :cat. This means that if h does not have a key k, h[k] will return :cat, nothing more, nothing less. As you can see above, executing h[k] does not change the hash when k is :c or :d.
On the other hand,
h[:c] = h[:c]
  #=> :c
h #=> {:a=>1, :b=>2, :c=>:cat}

Confused? Let me write this without the syntactic sugar:
h.[]=(:d, h.[](:d))
  #=> :cat
h #=> {:a=>1, :b=>2, :d=>:cat}

The default value is returned by h.[](:d) (i.e., h[:d]) whereas Hash#[]= is an assignment method (that takes two arguments, a key and a value) to which the default does not apply.
A common use of this default is to create a counting hash:
a = [1,3,1,4,2,5,4,4]
h = Hash.new(0)
a.each { |x| h[x] = h[x] + 1 }
h #=> {1=>2, 3=>1, 4=>3, 2=>1, 5=>1}

Initially, when h is empty and x #=> 1, h[1] = h[1] + 1 will evaluate to h[1] = 0 + 1, because (since h has no key 1) h[1] on the right side of the equality is set equal to the default value of zero. The next time 1 is passed to the block (x #=> 1), x[1] = x[1] + 1, which equals x[1] = 1 + 1. This time the default value is not used because h now has a key 1.
This would normally be written (incidentally):
a.each_with_object(Hash.new(0)) { |x,h| h[x] += 1 }
  #=> {1=>2, 3=>1, 4=>3, 2=>1, 5=>1}

One generally does not want the default value to be a collection, such as an array or hash. Consider the following:
h = Hash.new([])
[1,2,3].map { |n| h[n] = h[n] }
h #=> {1=>[], 2=>[], 3=>[]}

Now observe:
h[1] << 2
h #=> {1=>[2], 2=>[2], 3=>[2]}

This is normally not the desired behaviour. It has happened because
h.map { |k,v| v.object_id }
  #=> [25886508, 25886508, 25886508]

That is, all the values are the same object, so if the value of one key is changed the values of all other keys are changed as well.
The way around this is to use a block when defining the hash:
h = Hash.new { |h,k| h[k]=[] }
[1,2,3].each { |n| h[n] = h[n] }
h #=> {1=>[], 2=>[], 3=>[]}
h[1] << 2
h #=> {1=>[2], 2=>[], 3=>[]}
h.map { |k,v| v.object_id }
  #=> [24172884, 24172872, 24172848]

When the hash h does not have a key k the block { |h,k| h[k]=[] } is executed and returns an empty array specific to that key.
Comment: so then, it looks like `h = Hash.new {|hsh, key| hsh[key] = [] }` is what would be desired... `h = Hash.new { [] }` doesn't have the effect so that `h[1].push(123)` and `h[2].push(456)` and then `p h` will show the hash with 2 keys and 2 arrays
Comment: You are correct. Thanks. I edited.
Comment: The [documentation](http://ruby-doc.org/core-2.4.1/Hash.html#method-c-new) could be a little clearer on this: "If _obj_ is specified, this single object will be used for all _default values_. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required." The last sentence implies but doesn't explicitly specify how the default value works.
Comment: @muistooshort, I experienced a brain vapour-lock.  (The block returns the object regardless of whether it's the last calculation, of course.) Deleted my earlier comments. Yes on `{ |h,k| [] }` (same as `{ [] }`), which in my example results in, for example, `[] << 1 #=> [1]`, but since `[1]` is not tied to the hash, it is merely garbage-collected and `{}` is returned by the block. Readers should take note that the block can also contain statements that perform actions that have nothing to do with computing a default value.
Answer: The statement:
foo = Hash.new([])

creates a new Hash that has an empty array ([] as default value). The default value is the value returned by Hash::[] when its argument is not a key present in the hash.
The statement:
foo[123]

invokes Hash::[] and, because the hash is empty (the key 123 is not present in the hash), it returns a reference to the default value which is an object of type Array.
The statement above doesn't create the 123 key in the hash.
Ruby objects are always passed and returned by reference. This means that the statement above doesn't return a copy of the default value of the hash but a reference to it.
The statement:
foo[123].push("hi")

modifies the above mentioned array. Now, the default value of the foo hash is not an empty array any more; it is the array ["hi"]. But the has is still empty; none of the above statements added some (key, value) pair to it.

How is it that foo[123] has a value

foo[123] doesn't have any value, the key 123 is not present in the hash (the hash is empty). A subsequent call to foo[123] returns a reference to the default value again and the default value now it's ["hi"]. And a call to foo[456] or foo['abc'] also returns a reference to the same default value.
Comment: so maybe in most situations, that really is not a desired behavior? who want to "morph" a default value? it has side effect and is dangerous
Comment: The side effect comes from the incorrect interpretation of what the line `foo[123].push("hi")` does. If you want it to set the array `["hi"]` at key `123` in the `foo` hash then this approach is valid in PHP f.e. (with a different syntax) but not in Ruby.
Comment: I think the bottom line here is: in Ruby, the method [`Hash#[]`](https://ruby-doc.org/core-2.4.0/Hash.html#method-i-5B-5D) never creates an entry in the hash when a non-existing key is accessed (PHP, for example, does it in some contexts). You have to use [`Hash#[]=`](https://ruby-doc.org/core-2.4.0/Hash.html#method-i-5B-5D-3D) in order to create a new entry in the hash. And don't forget Ruby handles everything using references.
Answer: You didn't actually change the value of key 123, you're just accessing the default value [] you provided during initialization. You can confirm this if you inspect a different value like foo[0].
If you would do this:
foo[123] = ["hi"]

you could see the new entry, because you've created a new array under the key 123.
Edit

When you call foo[123].push("hi"), you're mutating the (default) value instead of adding a new entry.
Calling foo[123] += ["hi"] creates a new array under the given key, replacing the previous one if it existed, which will show the behavior you desire.
Comment: I think the confusion comes from "mutating" or not mutating... it is not relevant. The key point is that it is **one instance of Array**, sitting there, so whenever the key doesn't exist, then this very same instance is returned... usually not what the programmer wants
Comment: the usage `foo[123] += ["hi"]` works. However, if some other programmers actually did a `foo[:bar].push("hi")`, then it will start to have side effect for any other code that does `foo[123] += ["hi"]`. I really do not like side effect like this
Comment: it is like a dangling default value (a dangling Array instance), subject to anybody's tampering... it seems dangerous
Comment: It is the way hashes handle default value. If, during lookup, no such key exists, it will just return the single default value set, which is an array reference in this instance.
Comment: Works just the same way with integers or strings as well, only we usually create new integers and strings instead of mutating the previous value.
Comment: See the difference: `h = Hash.new("hello"); h[1] += " world"; h[2] << " ruby"`
Answer: Printing out the hash with:
p foo
only prints the values stored in the hash.  It does not display the default value (or anything added to the default array).
When you execute:
p foo[123]

Because 123 does not exist, it access the default value.
If you added two values to the default value:
foo[123].push("hi")
foo[456].push("hello")

your output would be:
p foo       # => {}
p foo[123]  # => ["hi","hello"]
p foo       # => {}

Here, poo[123] does again still not exist, so it prints out the contents of the default value.
Comment: Take a look at my answer, I provided an alternative way to update keys. :)
Comment: ok... I think I get it. It is one instance of an empty array. It won't be a `dup` of an empty array each time... so `foo[123]` and `foo[345]` all refer to this very same array instance... so it is a bit weird... a dictionary that has its key and value pairs, and any non-key maps to this one single array instance...
Comment: it can be error prone too... if some code is `foo[key] = foo[key] || []`... and then if someone else accidentally set `foo[:wah]`... then my first line of code is "messed up". Then I may as well just use `foo = Hash.new()` and not worry about this dangling array instance.
Comment: `.push()` is not a `Hash` method.  It is part of the `Array` class.  You get an `Array` as your default value because you specify it in `foo = Hash.new([])`.
Comment: I think the main point is that it is one instance of Array, not multiple... oh well... or use `Hash.new {|hsh, key| hsh[key] = [] }` if you want to expected behavior as you hoped for... it is a bit verbose


in SwiftUI, in a ForEach(0 ..< 3), animate the tapped button only (not all 3), animate the other 2 differently

Question: After a full day trying to animate these buttons I give up and ask for help.
I would like to animate the correct button only like this:
.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 0, y: 1, z: 0))
and at the same time make the other two buttons fade out to 25% opacity.
When the player clicks the wrong button I would like to
animate the wrong button like this:
.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 1, y: 1, z: 1)) (or anyway else you can think to indicate disaster) and leave the other two alone.
After that happened I would like the alert to show.
Below is my code. I commented what I would like to do and where if at all possible.
It all works like I want but cannot get the animation going.
Thanks for your help in advance
    import SwiftUI

struct ContentView: View {
   @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"]
        @State private var correctAnswer = Int.random(in: 0...2)
        @State private var showingScore = false
        @State private var scoreTitle = ""
        @State private var userScore = 0
        @State private var userTapped = ""
         @State private var animationAmount =  0.0

        var body: some View {
            ZStack {
                LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom)
                    .edgesIgnoringSafeArea(.all)

                VStack(spacing: 20) {
                    VStack {
                        Text("Tap the flag of...")
                            .foregroundColor(.white).font(.title)
                        Text(countries[correctAnswer])
                            .foregroundColor(.white)
                            .font(.largeTitle).fontWeight(.black)
                    }

                    ForEach(0 ..< 3) { number in
                        Button(action: {
                                self.flagTapped(number)
                            if self.correctAnswer == number {
                                //animate the correct button only like this:
                                //.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 0, y: 1, z: 0))
                                // and
                                // make the other two buttons fade out to 25% opacity
                            } else {
                                // animate the wrong button like this:
                                //.rotation3DEffect(.degrees(self.animationAmount), axis: (x: 1, y: 1, z: 1))
                            }
                        }) {
                            Image(self.countries[number])
                                .renderingMode(.original)
                                .clipShape(Capsule())
                                .overlay(Capsule().stroke(Color .black, lineWidth: 1))
                                .shadow(color: .black, radius: 2)
                        }
                    }

                    Text ("your score is:\n \(userScore)").foregroundColor(.white).font(.title).multilineTextAlignment(.center)
                }

            }
            .alert(isPresented: $showingScore) {
                Alert(title: Text(scoreTitle), message: Text("You chose the flag of \(userTapped)\nYour score is now: \(userScore)"), dismissButton: .default(Text("Continue")) {
                    self.askQuestion()
                    })
            }
        }
        func flagTapped(_ number: Int) {
            userTapped = countries[number]
            if number == correctAnswer {
                scoreTitle = "Correct"
                userScore += 1
            } else {
                scoreTitle = "Wrong"
                userScore -= 1
            }
            showingScore = true
        }

        func askQuestion() {
            countries.shuffle()
            correctAnswer = Int.random(in: 0...2)
        }

    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Answer: I had the same problem. Here is my solution (only the code that's different from yours):
The ForEach:
ForEach(0 ..< 3, id: \.self){ number in
                Button(action: {
                    withAnimation{
                        self.tappedFlag = number
                        self.flagTapped(number)
                    }
                }){
                    FlagImage(imageName: self.countries[number])
                }
                .rotation3DEffect(.degrees(self.isCorrect && self.selcectedNumber == number ? 360 : 0), axis: (x: 0, y: 1, z: 0))
                .opacity(self.isFadeOutOpacity && self.selcectedNumber != number ? 0.25 : 1)

                .rotation3DEffect(.degrees(self.wrongAnswer && number != self.correctAnswer ? 180 : 0), axis: (x: 1, y: 0, z: 0))
                .opacity(self.wrongAnswer && number != self.correctAnswer ? 0.25 : 1)

            }

The alert:
.alert(isPresented: $showingScore){
        if scoreTitle == "Correct"{
            return Alert(title: Text(scoreTitle), message: Text("Your score is \(userScore)"), dismissButton: .default(Text("Continue")){
                    self.askQuestion()
                })
        }else{
            return Alert(title: Text(scoreTitle), message: Text("That is the flag of \(countries[tappedFlag]), you lost one point!"), dismissButton: .default(Text("Continue")){
                self.askQuestion()
            })
        }
    }

The two functions:
func flagTapped(_ number: Int){
    self.selcectedNumber = number
    self.alreadyTapped = true
    if number == correctAnswer{
        scoreTitle = "Correct"
        userScore += 1
        self.isCorrect = true
        self.isFadeOutOpacity = true
    }else{
        self.wrongAnswer = true
        scoreTitle = "Wrong"
        if userScore != 0{
            userScore -= 1
        }
    }

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
        self.showingScore = true
    }
}

func askQuestion(){
    countries = countries.shuffled()
    correctAnswer = Int.random(in: 0...2)
    self.isCorrect = false
    self.isFadeOutOpacity = false
    self.wrongAnswer = false
}

You have to declare some new variables :)
I hope I could help.
PS: There is a playlist on Youtube for 100DaysOfSwiftUI with the solutions to almost every own task.
https://www.youtube.com/watch?v=9AUGceRIUSA&list=PL3pUvT0fmHNhb3qcpvuym6KeM12eQK3T1
Comment: Thanks Lukas, your code worked like a charm for me. I adapted it to my version and it did the job. I will investigate the link, thanks for that too. I am learning but sometimes get stuck in a glass of water. The latest hurdle for me is an error that I have a hard time to resolve: The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions. I hope I will solve that as well then I am done with the flags. Nothing wrong with the code just too much for the compiler.
Comment: I'm glad I could help. For your compiler problem, maybe this article will help you:

https://www.hackingwithswift.com/example-code/language/how-to-fix-the-error-expression-was-too-complex-to-be-solved-in-reasonable-time
Comment: Thanks again Lukas. I read the  hackingwithswift tutorial: very interesting. My problem with the "The compiler is unable to type-check" error was a fake. I pasted a previous version in place of the buggy one, applied the changes manually, one by one again, starting from the variables downwards and compiled each change successfully. It never failed again. Go figure!
Answer: I had a problem similar to yours when solving this challenge. I figured out a solution without using DispatchQueue.main.asyncAfter. I made the following as the final solution:

Spin around 360 degrees the correct chosen flag and fade out the other flags to 25 % of opacity.
Blur the background of the wrong flag chosen with red and fade out the other flags to 25 % of opacity.

Here is the full solution (I comment on the parts that were important to achieve the above solution):
import SwiftUI

// Create a custom view
struct FlagImage: View {
    var countryFlags: String

    var body: some View {
        Image(countryFlags)
            .renderingMode(.original)
            .clipShape(Capsule())
            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
            .shadow(color: .black, radius: 2)
    }
}

struct ContentView: View {

    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()

    @State private var correctAnswer = Int.random(in: 0...3)
    @State private var showingScore = false
    @State private var scoreTitle = ""

    @State private var userScore = 0

    // Properties for animating the chosen flag
    @State private var animateCorrect = 0.0
    @State private var animateOpacity = 1.0
    @State private var besidesTheCorrect = false
    @State private var besidesTheWrong = false
    @State private var selectedFlag = 0

    var body: some View {

        ZStack {
            LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)

            VStack(spacing: 30) {

                VStack {
                    Text("Tap on the flag!")
                        .foregroundColor(.white)
                        .font(.title)

                    Text(countries[correctAnswer])
                        .foregroundColor(.white)
                        .font(.largeTitle)
                        .fontWeight(.black)
                }

                ForEach(0 ..< 4) { number in
                    Button(action: {

                        self.selectedFlag = number

                        self.flagTapped(number)

                    }) {

                        FlagImage(countryFlags: self.countries[number])
                    }
                    // Animate the flag when the user tap the correct one:
                    // Rotate the correct flag
                    .rotation3DEffect(.degrees(number == self.correctAnswer ? self.animateCorrect : 0), axis: (x: 0, y: 1, z: 0))
                    // Reduce opacity of the other flags to 25%
                    .opacity(number != self.correctAnswer && self.besidesTheCorrect ? self.animateOpacity : 1)

                    // Animate the flag when the user tap the wrong one:
                    // Create a red background to the wrong flag
                    .background(self.besidesTheWrong && self.selectedFlag == number ? Capsule(style: .circular).fill(Color.red).blur(radius: 30) : Capsule(style: .circular).fill(Color.clear).blur(radius: 0))
                    // Reduce opacity of the other flags to 25% (including the correct one)
                    .opacity(self.besidesTheWrong && self.selectedFlag != number ? self.animateOpacity : 1)

                }
                Spacer()

                Text("Your total score is: \(userScore)")
                    .foregroundColor(Color.white)
                    .font(.title)
                    .fontWeight(.black)

                Spacer()

            }
        }
        .alert(isPresented: $showingScore) {
            Alert(title: Text(scoreTitle), dismissButton: .default(Text("Continue")) {
                self.askQuestion()
                })
        }

    }

    func flagTapped(_ number: Int) {

        if number == correctAnswer {
            scoreTitle = "Correct!"

            userScore += 1

            // Create animation for the correct answer
            withAnimation {
                self.animateCorrect += 360
                self.animateOpacity = 0.25
                self.besidesTheCorrect = true
            }
        } else {
            scoreTitle = "Wrong!"

            // Create animation for the wrong answer
            withAnimation {
                self.animateOpacity = 0.25
                self.besidesTheWrong = true
            }
        }
        showingScore = true
    }

    func askQuestion() {
        // Return the booleans to false
        besidesTheCorrect = false
        besidesTheWrong = false
        countries = countries.shuffled()
        correctAnswer = Int.random(in: 0...3)
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Basically, my solution is to add ternary operators inside the view modifiers (e.g., .rotation3DEffect(...), .opacity(...) and .background(...)) after the Button view. The tricky part is to correctly combine the checking condition.
I prefer to add the withAnimation modifier to my flagTapped function. In this place I have more control of the animations if the user select a correct or a wrong flag.
I made a small change to the original challenge: just add one more flag to the view.
The final result when a user presses the correct and wrong flag is here:
.
Comment: Hi Carlos, thank you for your contribution. I like the idea of showing the right and wrong answer clear of the alert. I will give it a go. Have a nice day!
Answer: this is an old question, but still I guess I found partial solution for this and it might help future students too. My solution is not a perfect one and it is a bit clumsy, but maybe it may help others to come up with a better one.
What I saw from the task itself you have to animate each button and fadeout those, which were not tapped. However if you apply the animation to all of the views made with forEach and they all are attached to the same variable, the animation will be triggered for all of them:
My solution was to split this animation variables into an array with indexes of the flags and change only variables attached to the flag tapped or not tapped.
This is my complete code:
struct ContentView: View {
@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Monaco", "Nigeria", "Poland", "Spain", "UK", "US"].shuffled()
@State private var title = ""
@State private var isDisplayed = false
@State private var rightAnswer = Int.random(in: 0...2)
@State private var messageText = ""
@State private var score = 0
@State private var answersCount = 0
@State private var modalButtonText = ""
@State private var animationRotation = [0.0, 0.0, 0.0]
@State private var viewAnimation = 0.0
@State private var opacity = [1.0, 1.0, 1.0]

var body: some View {
    ZStack {
        Color(red: 239, green: 239, blue: 239)
            .ignoresSafeArea()
        VStack (spacing: 50){
            Spacer()
            VStack {
                Text("Guess the Flag")
                    .font(.subheadline.weight(.semibold))
                Text(countries[rightAnswer])
                    .font(.largeTitle.bold())
            }
            VStack (spacing: 30) {

                ForEach(0...2, id: \.self) {country in
                    Button {
                        checkCard(country)
                    } label: {
                        FlagView(index: country, arrayOfCountries: countries)
                    }.rotation3DEffect(Angle(degrees: animationRotation[country]), axis: (x: 0, y: 1, z: 0)).opacity(opacity[country])
                }.rotation3DEffect(Angle(degrees: viewAnimation), axis: (x: 0, y: 1, z: 0))
                Spacer()
                Text("Score: \(score)").TitleStyle()
                Spacer()
            }
        }
    }
    .alert(title, isPresented: $isDisplayed) {
        Button(modalButtonText) {
            newQuestion()
        }
    } message: {
        Text(messageText)
    }
}

func checkCard(_ number: Int) {

    if number == rightAnswer {
        modalButtonText = "Continue"
        title = "Correct"
        messageText = "You scored 1 point"
        score += 1
    } else {
        modalButtonText = "Continue"
        title = "Incorrect"
        messageText = "You lost 1 point"
        if score > 0 {
            score -= 1
        }
    }
    if answersCount > 8 {
        modalButtonText = "Restart"
        messageText = "This was the last one"
    }

    withAnimation(.easeIn(duration: 1.0)) {
        animationRotation[number] -= 360
        for i in 0...2 {
            if i != number {
                opacity[i] = 0.25
            }
        }
    }
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in
        isDisplayed = true
    }

}

func newQuestion(){

    countries.shuffle()
    rightAnswer = Int.random(in: 0...2)
    for i in 0...2 {
        opacity[i] = 1.0
    }

    withAnimation(.easeIn(duration: 0.5)) {
        viewAnimation += 180
    }
    if answersCount > 8 {
        score = 0
        answersCount = 0
    } else {
        answersCount += 1
    }

}

}
These are the solution parts:
@State private var animationRotation = [0.0, 0.0, 0.0]
@State private var opacity = [1.0, 1.0, 1.0]

Here we create two variables of arrays with relevant values
ForEach(0...2, id: \.self) {country in
                    Button {
                        checkCard(country)
                    } label: {
                        FlagView(index: country, arrayOfCountries: countries)
                    }.rotation3DEffect(Angle(degrees: animationRotation[country]), axis: (x: 0, y: 1, z: 0)).opacity(opacity[country])
                }.rotation3DEffect(Angle(degrees: viewAnimation), axis: (x: 0, y: 1, z: 0))

in ForEach View we call assign those variables to each of the animation modifiers properties
        withAnimation(.easeIn(duration: 1.0)) {
        animationRotation[number] -= 360
        for i in 0...2 {
            if i != number {
                opacity[i] = 0.25
            }
        }
    }
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in
        isDisplayed = true
    }

Setting delay so I can show animation before the alert pops up and changing the opacity of other flags that were not selected with loop


Derivative and vector for start of curve are orthogonal to fixed vector, hence the curve is

Question:
Let $\alpha:I\to\Bbb R^3$ be a parameterized curve and let $v\in \Bbb R^3$ be a fixed vector. Assume that $\alpha'(t)$ is orthogonal to $v$ for all $t\in I$, and that $\alpha(0)$ is also orthogonal to $v$. Prove that $\alpha(t)$ is orthogonal to $v,\forall t\in I$.

I have been having trouble solving this problem, and I have written it in math as follows:
$$v_1x'(t)+v_2y'(t)+v_3z'(t)=0=v_1x(0)+v_2y(0)+v_3z(0)$$
and using this I want:
$$v_1x(t)+v_2y(t)+v_3z(t)=0$$
Can I have a hint please?
Comment: Is this from Do Carmo's text?
Comment: @Tucker Page 5, Q4
Answer: $$\alpha(t)-\alpha(0)=\int_{0}^{t}\alpha'(\tau)d\tau$$
Dotting both sides with $v$
$$v\cdot\alpha(t)-v\cdot\alpha(0)=\int_{0}^{t}v\cdot\alpha'(\tau)d\tau$$
The integrand is identically zero and so
$$v\cdot\alpha(t)-v\cdot \alpha(0)\equiv 0 \Rightarrow v\cdot\alpha(t)\equiv 0$$
Answer: Your condition that $\alpha'(t)\perp v$ for all $t$ is the same as saying that $\langle\alpha'(t),v\rangle =0$ for all $t$, but note also that $\frac{d}{dt}\langle\alpha(t),v\rangle = \langle\alpha'(t),v\rangle$ since the dot product is linear in the first coordinate. Therefore, $\langle\alpha(t),v\rangle$ is constant, and you can conclude.
Comment: Yes, otherwise there would be another term from the product rule.
Comment: I haven't come across $\frac{d}{dt}\langle \alpha(t),v\rangle = \langle \alpha'(t),v\rangle$ before, can you verify that for me if it's not too much trouble?
Comment: $<\alpha(t),v>=\alpha_{x}v_{x}+\alpha_{y}v_{y}+\alpha_{z}v_{z}$  $\frac{d}{dt}<\alpha(t),v>=\frac{d}{dt}(\alpha_{x}v_{x})+\frac{d}{dt}(\alpha_{y}v_{y})+\frac{d}{dt}(\alpha_{z}v_{z})$
Comment: OH wait, it is verified, it's just that $v'(t)=0$
Comment: Oh yes, oops, thanks @Tucker and Alexander. With the latex its `\langle \rangle` = $\langle \rangle$


Alterar cor de radio button

Question: Tenho um aplicativo que possui fundo preto. Em uma das telas do aplicativo tenho um RadioButton. Eu preciso alterar a cor desse RadioButtom para que ele apareça na tela.
<android.support.v7.widget.AppCompatRadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New RadioButton"
    android:id="@+id/radioButton"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:buttonTint="#FFF" />

O problema é que em versões mais antigas do Android isso não funciona, ou seja, a cor não é alterada. Alguém poderia me ajudar com isso?
Comment: Breno, conseguiu resolver seu problema com a resposta? Ou precisa de mais alguma informação?
Answer: Existem várias alternativas, uma delas é criar um RadioButton personalizado usando duas imagens:

Assim você pode criar um radio_button_personalizado utilizando-as:
radio_button_personalizado.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_checked="true" android:drawable="@drawable/checkedradiobutton" />
     <item android:state_checked="false" android:drawable="@drawable/unchekedradiobutton" />
</selector>

Assim você pode definir o android:button como radio_button_personalizado:

Screenshot

Detalhes

Custom Radio Button in Android
Customizing Radio Button
Comment: Boa, me ajudou aqui.
Comment: @FlavioMisawa conseguiu resolver o problema?!
Comment: Deu certo pra mim sim o/ Valewz

Alterar cor de radio button


Autocorrelation of convolution integral

Question: Work out the autocorrelation
$r_Y(\tau) = E[Y(t)Y(t+\tau)]$
with
$Y(t) = \int_{-\infty}^{\infty} h(t-u) x(u)$
and
$X$ a WSS, ergodic process
I always get: $h(t)* h(t+\tau) * r_X(\tau)$  (with $*$ convolution)
My approach
(after multiplication)
$\int h(t-u)  ( \int h(t+\tau -u')r_X(u'-u) \text{d}u' ) \text{d}u$
The inner integral is the definition of a convolution hence
$= \int h(t-u)  ( h(t+\tau)*r_x(t+\tau-u) ) \text{d}u$
This gives again a convolution integral with time variable t. so,
$= h(t)* h(t+\tau) * r_X(\tau) $
Correct solution:
$  r_X(\tau) * h(\tau) * h(-\tau) $
Question
What am I doing wrong?
Comment: This question is difficult because the notation doesn't make sense. Presumably, $h=g$. (If not, what is $h$?) Convolution is an operation on *functions* whereas expressions like $h(\tau)$ and $h(-\tau)$ are *numbers.* Thus, for instance, it makes sense to write expressions like $$(h * r_X)(t)=\int_\mathbb{R}h(t-u)r_X(u)du$$ but this is *not* equal to "$h(t)*r_X(t)$," which has no meaning. Because of this confusion, after a good start to the solution things begin to go awry at the second step when "$*$" first appears. If you straighten out this notation you might find the problem is simple.
Comment: @whuber Thank you for clearing this up. So that means that the presented solution is nonsense?
Comment: I'm not sure--it depends on what you really mean by the "$h$" notation.  I'm struggling to make sense of it, but maybe I'm overlooking something that's obvious to you.
Comment: @whuber sorry. I've corrected it (g had to be h)  h is the impulse response of a linear system.
Answer: An adapted and enhanced version of
an answer of mine on dsp.SE
Suppose that
$$\begin{align*}
Y(t) &= \int_{-\infty}^{\infty} h(s)X(t-s)\,\mathrm ds \tag{1}
\end{align*}
$$
If we define the crosscorrelation function $R_{X,Y}(\tau)$ as
$$R_{X,Y}(\tau) = E[X(t-\tau)Y(t)],\tag{2}$$ then
$$\begin{align*}
R_{X,Y}(\tau) &= E\left[X(t-\tau)\int_{-\infty}^{\infty} h(s)X(t-s)\,\mathrm ds\right]\\
&= \int_{-\infty}^{\infty} h(s)E[X(t-\tau)X(t-s)]\,\mathrm ds\\
&= \int_{-\infty}^{\infty} h(s)R_X(\tau-s)\,\mathrm ds.
\end{align*}$$
In short,
$R_{X,Y} = h\star R_X.$
Next, consider
$$\begin{align}
R_Y(\tau) &= E[Y(t-\tau)Y(t)]\\
&= E\left[\int_{-\infty}^{\infty} h(s)X(t-\tau-s)\,\mathrm ds \,Y(t)\right]
&{\scriptstyle{\text{substituting from} ~ (1)}}\\
&= \int_{-\infty}^{\infty} h(s) E[X(t-\tau-s)Y(t)]\,\mathrm ds\\
&= \int_{-\infty}^{\infty} h(s) R_{X,Y}(\tau+s)\,\mathrm ds\\
&= \int_{-\infty}^{\infty} \tilde{h}(-s) R_{X,Y}(\tau+s)\,\mathrm ds
&{\scriptstyle{\tilde{h}(t) = h(-t)\ \forall \, t ~\text{is the time-reversed impulse response}}}\\
&= \int_{-\infty}^{\infty} \tilde{h}(\lambda) R_{X,Y}(\tau-\lambda)\,\mathrm d\lambda
&{\scriptstyle{\text{substitute}~ \lambda = -s}}
\end{align}$$
that is, $R_Y = \tilde{h}\star R_{X,Y}$, and it follows that
$$R_Y = \tilde{h}\star h \star R_X = (\tilde{h}\star h)\star R_X = R_h\star R_X$$
where $\tilde{h}(t) = h(-t)$ for all $t$ is the time-reversed impulse response
and $R_h = \tilde{h}*h$ is the autocorrelation function of the
deterministic signal $h(t)$.  Translated to the frequency domain, this gives the
power spectral density relationship
$$S_Y(f) = |H(f)|^2 S_X(f).$$

Autocorrelation of convolution integral


iptables connlimit triggering unexpectedly

Question: I've been using these firewall rules:
-I FORWARD -p tcp --syn -m connlimit --connlimit-above 50 -j REJECT
-I FORWARD -p tcp --syn -m connlimit --connlimit-above 50 -j LOG --log-prefix "CONNLIMIT: " --log-level debug

it seems straightforward enough: prevent someone from opening more than 50 connections and causing a denial of service. I've tested it successfully against slowloris. I turned the limit up to 50 specifically to prevent issues with false-positives (Apache can be very connection-hungry.) however, this morning, I get an email from my Nagios monitor and my logs show several lines of "CONNLIMIT" with the source IP being my monitoring system.
I have no idea why this is happening. at most, my monitoring server should be performing 5-10 checks and perhaps a ping or SSH connection. I'd be shocked if I had more than 25 conncetions open, yet 2 weekends in a row, I've managed to trigger connlimit 50 and rudely awaken myself.
is there something wrong with my firewall rules? (maybe add the 'new' flag?) is Nagios not closing its connections properly? I'm not even sure how to continue debugging this issue without logging every packet on the wire and patiently waiting for my cell phone to go off at some awful hour.
[edit: just for fun, here's the server logs]
Oct  9 11:33:22 adapt kernel: [1888526.442640] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=60 TOS=0x00 PREC=0x00 TTL=54 ID=2076 DF PROTO=TCP SPT=46536 DPT=80 WINDOW=5840 RES=0x00 SYN URGP=0
Oct  9 11:34:22 adapt kernel: [1888586.443869] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=60 TOS=0x00 PREC=0x00 TTL=54 ID=43048 DF PROTO=TCP SPT=57931 DPT=80 WINDOW=5840 RES=0x00 SYN URGP=0
Oct  9 11:35:42 adapt kernel: [1888667.011376] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=64 TOS=0x00 PREC=0x00 TTL=54 ID=19161 DF PROTO=TCP SPT=63669 DPT=80 WINDOW=65535 RES=0x00 SYN URGP=0
Oct  9 11:35:48 adapt kernel: [1888673.093663] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=64 TOS=0x00 PREC=0x00 TTL=54 ID=48302 DF PROTO=TCP SPT=63673 DPT=80 WINDOW=65535 RES=0x00 SYN URGP=0
Oct  9 11:35:53 adapt kernel: [1888678.361267] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=64 TOS=0x00 PREC=0x00 TTL=54 ID=11711 DF PROTO=TCP SPT=63677 DPT=80 WINDOW=65535 RES=0x00 SYN URGP=0
Oct  9 11:36:04 adapt kernel: [1888688.517868] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=60 TOS=0x00 PREC=0x00 TTL=54 ID=6316 DF PROTO=TCP SPT=44206 DPT=443 WINDOW=5840 RES=0x00 SYN URGP=0
Oct  9 11:36:21 adapt kernel: [1888705.382273] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=64 TOS=0x00 PREC=0x00 TTL=54 ID=29613 DF PROTO=TCP SPT=63697 DPT=80 WINDOW=65535 RES=0x00 SYN URGP=0
Oct  9 11:36:49 adapt kernel: [1888733.467511] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=60 TOS=0x00 PREC=0x00 TTL=54 ID=52433 DF PROTO=TCP SPT=40930 DPT=22 WINDOW=5840 RES=0x00 SYN URGP=0
Oct  9 11:37:04 adapt kernel: [1888748.574700] CONNLIMIT: IN=eth0 OUT=eth1 SRC=[MONITOR] DST=[HOST] LEN=60 TOS=0x00 PREC=0x00 TTL=54 ID=26329 DF PROTO=TCP SPT=44223 DPT=443 WINDOW=5840 RES=0x00 SYN URGP=0

we can see that it's checking a few ports and issuing a check about once a minute.
Answer: You probably want recent not connlimit.
Here's an example from one of my hosts that limits SSH connections:
iptables -A INPUT -i eth0 -p tcp -m tcp --dport 22 -m state --state NEW -j SSH_Brute_Force
iptables -A SSH_Brute_Force -m recent --set --name SSH --rsource
iptables -A SSH_Brute_Force -m recent ! --update --seconds 120 --hitcount 5 --name SSH --rsource -j RETURN
iptables -A SSH_Brute_Force -m recent --update --name SSH --rsource
iptables -A SSH_Brute_Force -p tcp -j DROP

Or:

Only SSH packets have already been selected for entry into the chain
Assign connections to the "SSH" recent queue
Set a 120 second timeout, and a maximum of five new connections in that time, return the calling chain sessions that shouldn't be limited (calling chain then allows to good hosts)
Update the connection list
Drop packet
Comment: your rules led me to this site: http://hostingfu.com/article/ssh-dictionary-attack-prevention-with-iptables which seems to have slightly clearer rules. I'll read the man page, but mind briefly explaining what your rules are doing?
Answer: When the rule is triggered, do you see open connections from the monitor host in netstat?
What about in /proc/net/ip_conntrack on the router?
ISTR that connlimit actually limits all connections that hit this rule, and this is a very general rule. Is the number going up towards 50 due to other connections going through the router?
How about adding a debug rule to determine what's actually happening:
-I FORWARD -p tcp --syn -s [MONITOR] -j LOG --log-prefix "MONITOR CONNECT: " --log-level debug

Comment: /proc/net/ip_conntrack shows my monitor IP and another address that I've previously identified as a "problem." so it sounds like my iptables rule is actually incorrect? I dont mind if each source can only have 50 connections, but my goal IS NOT to limit the server to 50 total connections. unfortunately, I didnt think to check netstat until after I'd restored everything. its no fun getting SMS alerts in the middle of the night.


singular solution of an ODE

Question: Given $2y^2dx+(x-y+1)^2dy=0$ I need to find all possible solutions. so
$$
2y^2dx+(x-y+1)^2dy=0 \Longrightarrow y'=\frac{-2y^2}{(x-y+1)^2}
$$
changing variables to $v = x + 1$ and $u = y$
$$
u'=\frac{-2u^2}{(v-1-u+1)^2}=-2\frac{u^2}{(v-u)^2}=-2(\frac{u}{v-u})^2=-2(\frac{1}{(\frac{v-u}{u})})^2 = -2(\frac{1}{\frac{v}{u}-1})^2
$$
changing variables again $z=\frac{u}{v}$
$$
z'v+z=-2(\frac{1}{\frac{1}{z}-1})^2=\frac{-2z^2}{(1-z)^2}\Longrightarrow z'v=\frac{-2z^2-z(1-z)^2}{(1-z)^2}=\frac{-z(1-z^2)}{(1-z)^2}=\frac{-z(1+z)}{(1-z)}
$$
This is a separable equation so the solution is
$$
\int^z{\frac{1-u}{-u(1+u)}du}=\int^v{\frac{1}{t}dt}+C\Longrightarrow 2ln{|z+1|}-ln{|z|}=ln{C|v|}\Longrightarrow \frac{(z+1)^2}{z}=Cv\Longrightarrow (z+1)^2=Cvz
$$
and changing back to original variables I get
$$
(z+1)^2=Cvz \Longrightarrow (\frac{u}{v}+1)^2=Cv\frac{u}{v} \Longrightarrow (\frac{u+v}{v})^2=Cu \Longrightarrow (u+v)^2=Cuv^2 \Longrightarrow (y+x+1)^2=Cy(x+1)^2
$$
during this process I also get 2 singular solutions to $z$: $z=0$ and $z=-1$ going back to $y$ I get $y(x)=0, x\neq -1$ and $y=-x-1$ but when I try to use the second singular solution $y=-x-1$ I get $$y' = \frac{-2(-x-1)^2}{(x-(-x-1+1)^2}=\frac{-2(x+1)^2}{4(x+1)^2} = -\frac{1}{2}\neq -1 = (-x-1)'$$. Did I do something wrong along the way? can it be that the singular solution for z aren't singular for y?
Answer: $$\frac{-2z^2-z(1-z)^2}{(1-z)^2}=\frac{-2z^2-z+2z^2-z^3}{(1-z)^2}=\frac{-z(1+z^2)}{(1-z)^2}.$$ However, you wrote $$\frac{-2z^2-z(1-z)^2}{(1-z)^2}=\frac{-z(1-z^2)}{(1-z)^2}.$$ This was your mistake. So you should have $$z'v=\frac{-z(1+z^2)}{(1-z)^2}.$$ This is separable, but rather different from what you had, so the solution is going to look very different.
I leave the rest for you to solve.
EDIT: I will actually walk through the full problem now. I do not feel as though I am giving you the answer, since you clearly have put work into this. Walking through the full problem will help you see better every potential mistake.
When you solve differential equations, you typically want to avoid doing substitutions that involve the variable of the unknown function, and instead only do substitutions for the function itself. In this case, doing the substitution $v=x+1$ leads to the wrong result, as you will see later during the verification section of my answer. Thus, the verification is needed to calibrate the correct by undoing the shift that occurs due to this substitution. In fact, I believe a better approach would have been to substitute $z=\frac{y}{x+1}$ directly, which would have avoided the need for the verification.
Once you have $$z'v=\frac{-z(1+z^2)}{(1-z)^2},$$ there are two cases to consider. One case is when $z=0$. This already is a solution, so we can move on to the second case immediately, where $z\neq0$. Thus one has $$\frac{(1-z)^2}{z(1+z^2)}z'=-\frac{1}{v}.$$ Notice that $$\frac{(1-z)^2}{z(1+z^2)}=\frac{z^2-2z+1}{z(z^2+1)}=\frac{(z^2+1)-2\cdot{z}}{z(z^2+1)}=\frac{1}{z}-\frac{2}{z^2+1}.$$ Thus $$\left(\frac{1}{z}-\frac{2}{z^2+1}\right)z'=\frac{1}{v}.$$ Here, we need to be very careful. Because of the non-removable singularities at $z=0$ and $v=0$, we have four cases to consider: $z\lt0,v\lt0$; $z\lt0,v\gt0$; $z\gt0,v\lt0$; $z\gt0,v\gt0$. These four cases give, respectively, $$\ln(-z)-2\arctan(z)=-\ln(-v)+A,$$ $$\ln(-z)-2\arctan(z)=-\ln(v)+B,$$ $$\ln(z)-2\arctan(z)=-\ln(-v)+C,$$ $$\ln(z)-2\arctan(z)=-\ln(v)+D.$$ Exponentiating every equation gives $$-z\exp(-2\arctan(z))=A'\frac{1}{-v},$$ $$-z\exp(-2\arctan(z))=B'\frac{1}{v},$$ $$z\exp(-2\arctan(z))=C'\frac{1}{-v},$$ $$z\exp(-2\arctan(z))=D'\frac{1}{v}$$ with $A',B',C',D'\gt0$. The cases can be consolidated to simplify this into the complete piecewise result $$z\exp(-2\arctan(z))=\frac{\alpha}{-v}$$ if $v\lt0$ and $$z\exp(-2\arctan(z))=\frac{\beta}{v}$$ if $v\gt0$.
Unfortunately, I do not believe it is possible to solve for $z$ explicitly in closed-form, because I think there is no closed-form expression for the inverse function of $f$ defined by $f(z)=z\exp(-2\arctan(z))$ on $\mathbb{R}$. But in any case, $$z(v)=\begin{cases} f^{-1}\left(\frac{a}{v}\right)&v\lt0\\f^{-1}\left(\frac{b}{v}\right)&v\gt0\end{cases}$$ Since $z=\frac{y}{v}$, we have that $$y(v)=\begin{cases} vf^{-1}\left(\frac{a}{v}\right)&v\lt0\\vf^{-1}\left(\frac{b}{v}\right)&v\gt0\end{cases}$$ To verify, now consider taking the derivative. For example, just focus on $v\gt0$, for simplicity's sake. Since $f'(z)=\frac{f(z)}{z}-f(z)\frac{2}{z^2+1}$, $$y'(v)=f^{-1}\left(\frac{b}{v}\right)+v{1\over f'\left(f^{-1}\left(\frac{b}{v}\right)\right)}\cdot-\frac{b}{v^2}=\frac{y(v)}{v}-\frac{b}{v\left(\frac{f(f^{-1}(\frac{b}{v}))}{f^{-1}(\frac{b}{v})}-\frac{2f(f^{-1}(\frac{b}{v}))}{f^{-1}(\frac{b}{v})^2+1}\right)}=\frac{y(v)}{v}-\frac{b}{v\left(\frac{\frac{b}{v}}{f^{-1}(\frac{b}{v})}-\frac{2\frac{b}{v}}{f^{-1}(\frac{b}{v})^2+1}\right)}=\frac{y(v)}{v}-\frac{1}{\frac{1}{f^{-1}(\frac{b}{v})}-\frac{2}{f^{-1}(\frac{b}{v})^2+1}}=\frac{y(v)}{v}-\frac{1}{\frac{v}{vf^{-1}(\frac{b}{v})}-\frac{2v^2}{(vf^{-1}(\frac{b}{v}))^2+v^2}}=\frac{y(v)}{v}-\frac{1}{\frac{v}{y(v)}-\frac{2v^2}{y(v)^2+v^2}}=\frac{y(v)}{v}-\frac{1}{\frac{v(y(v)^2+v^2)}{y(v)(y(v)^2+v^2)}-\frac{2v^2y(v)}{y(v)(y(v)^2+v^2)}}=\frac{y(v)}{v}-\frac{y(v)(y(v)^2+v^2)}{vy(v)^2+v^3-2v^2y(v)}=\frac{vy(v)(y(v)^2+v^2)-2v^2y(v)^2}{v^2y(v)^2+v^4-2v^3y(v)}-\frac{vy(v)(y(v)^2+v^2)}{v^2y(v)^2+v^4-2v^3y(v)}=\frac{-2v^2y(v)^2}{v^2(v^2+y(v)^2-2vy(v))}=\frac{-2y(v)^2}{v^2+y(v)^2-2vy(v)}=\frac{2y(v)^2}{(v-y(v))^2}.$$ This verification assures that $$y(x)=\begin{cases} (x+1)f^{-1}\left(\frac{a}{x+1}\right)&x\lt{-1}\\(x+1)f^{-1}\left(\frac{b}{(x+1)}\right)&x\gt{-1}\end{cases}$$ for arbitrary real $a,b$ solves the original differential equation everywhere in $\mathbb{R}\setminus\{-1\}$. However, notice that if we had directly substituted $v=x+1$ into the solution we obtained prior to verification, we actually would have obtained shifted version of this solution, thus not the correct answer.
As for what Wolfram Alpha gave you, let us go back to $\ln((-1)^mz)-2\arctan(z)=-\ln((-1)^n(x+1))+A_{m,n}$. If you add $-\ln((-1)^n(x+1))$ to both sides of the equation, you get $\ln((-1)^{m+n}y)-2\arctan\left(\frac{y}{x+1}\right)=A_{m,n}$. Multiply by $-1$ on both sides to get $2\arctan\left(\frac{y}{x+1}\right)-\ln((-1)^{m+n}y)=-A_{m,n}$, which is what you obtained if you let $-A_{m,n}=C_{m,n}$. Now, $\arctan\left(\frac{1}{t}\right)=\operatorname{sgn}(t)\frac{\pi}{2}-\arctan(t)$, so $(-1)^{m+n}\pi-2\arctan\left(\frac{x+1}{y}\right)-\ln((-1)^{m+n}(x+1))=-A_{m,n}$, indicating that $-2\arctan\left(\frac{x+1}{y}\right)-\ln((-1)^{m+n}(x+1))=(-1)^{m+n-1}\pi-A{m,n}$, which is equivalent to $2\arctan\left(\frac{x+1}{y}\right)+\ln((-1)^{m+n}(x+1))=(-1)^{m+n}\pi+A_{m,n}$. As such, your solution and Wolfram Alpha's solution are equivalent, but there were some subtle technical details that needed to be taken care of.
Comment: So I fixed my mistake and now I get $2tan^{-1}{\frac{y}{x+1}}-ln{y}=C$ while on wolfarmalpha I get $ln{y}+2tan^{-1}{\frac{x+1}{y}}=C$ any idea where something might have flipped?
Comment: @CforLinux I edited my answer and expanded rather heavily on the solution, just to cover some technical details and be able to explain every possible doubt I can imagine you may have.
Comment: @Angel wouldn't the last definition for $y(x)$ actually be one for $x \neq -1$ i.e $y(x) = (x+1)f^{-1}(\frac{c}{x+1})\space    x \neq -1$? Also there is the $y\equiv 0$ solution for every $x \neq -1$
Comment: actually I find that this solution is correct as long as $y(x) \neq 0$ and $y \equiv 0$ is a singular solution as long as $x \neq -1$
Comment: @CforLinux *wouldn't the last definition for $y(x)$ actually be one for $x≠−1$ i.e $y(x)=(x+1)f^{−1}(\frac{c}{x+1}), x≠−1$?* No. You are assuming the antidifferentiation constant must be the same at both sides of the singularity, but this is not the case. If you have a different constant on both sides of the singularity, the resulting piecewise function still satisfies the differential equation, as demonstrating in my verification. Thus, those piecewise functions need to be included in the solution. So my solution is correct.
Comment: @CforLinux Also, notice that the solutions of the differential equation only solve the equation on $\mathbb{R}\setminus\{-1\}$, not on $\mathbb{R}$, and thus, $y\equiv0$ is included in my solution, with $a=b=0$. Now, $y\equiv0$ can be differentiably extended to $\mathbb{R}$, and it is the only solution with this property, but this is completely irrelevant to the question at hand.

singular solution of an ODE


How to find effective rate of interest?

Question: A man charges at the rate of $10$ paise per rupee per month, payable in advance. What effective rate of interest does he charges per annum?
Here rate is $10\%$ per month. So to change it in per annum, I divided it by $12$ and set $n$ to $1$.
$$\text{effective rate}=\left(1+ \frac{r}{100}\right)^n -1$$
After applying the formula, I got
$$\left(1+ \frac {10}{1200}\right) -1$$
But I am getting the wrong answer and the correct answer is $254.5\%$. Please help me understand this.
Comment: One Rupee = 100 paisa
Comment: Feel free to [mark one of the answers as accepted](https://math.stackexchange.com/help/someone-answers) by clicking the check mark (✓) icon next to the answer on the left. Doing so will mark the question as answered, and will also award both you and the author of the answer a few reputation points. Also note that users that [accept good answers](https://math.meta.stackexchange.com/help/accepted-answer) are also more likely to have their future questions answered.
Answer: Since the man charges interest at the rate of $10$ paise per rupee per month, payable in advance, this implies that $10$ paise can be treated as interest on $90$ paise.
For example, if you borrow $100$ paise and pay $10\%$ interest in advance, then you have only borrowed $90$ paise. Therefore the monthly interest rate $j$ is calculated as follows
$$j=\frac{10}{100-10}=\frac{10}{90}=\frac19$$
Since we already know the monthly interest rate, we can use the following to find the effective interest rate
$$r=\left(1+j\right)^{12}-1$$
If you're curious about the annual nominal interest rate, simply multiply the monthly interest rate by $12$.
$$i=12j=\frac{12}{9}=\frac{4}{3}$$
Which would allow you to use the following
$$r=\left(1+\frac{i}{12}\right)^{12}-1$$
Both approaches eventually show that $r\approx 2.545$, after rounding.
$$r=\left(1+\frac19\right)^{12}-1$$
$$\log_{10}\left(r+1\right)=12\log_{10}\left(\frac{10}{9}\right)$$
$$r=10^{12\left(1-\log_{10}9\right)}-1$$
At this point, the author used
$$\log_{10}9\approx 0.9542$$
Which leads to the following
$$r\approx 10^{0.5496}-1$$
Surely you can take it from here.
Comment: can you explain how 10 paise treated as interest on 90 paise?
Comment: @KanwaljitSingh I have added an explanation.
Comment: @KanwaljitSingh I have amended this explanation and added more details.
Comment: Can you please show me the calculations then i will accept your answer.
Comment: And in formula r/100. Why not you use divided by 100?
Comment: @JohnAmar, I've updated my post.
Answer: You pay $10$ in advance to have $100$, that is you obtain $90$ leaving $10$ as interest; so you have a monthly interest rate of
$$
i_m=\frac{10}{90}=11.11\%
$$
So you have that the yearly interet rate is $i$, given by
$$
(1+i_m)^{12}=1+i\qquad\Longrightarrow\qquad i=(1+i_m)^{12}-1\approx 254.1\%
$$
Comment: Show me the calculations also.
Answer: My answer is 213.84%
$(1+0.1)^{12}-1=2.1384$
The formula is $(1+\frac{r}{n})^{n}-1$ where r stands for annual interest rate and n stands for number of compounding periods per year. Since 10% is the monthly rate, $\frac {r}{n}$=0.1, n=12
Comment: here advance payment of interest pay any role?

How to find effective rate of interest?


Get map center location while moving around

Question: I want to get the center coordinates of the map while the user is moving on it. I have to repopulate the map overlays depending on the current position of the map (the current center). Are there some listeners to listen on map panning or map moving? I know there is a myMapView.getMapCenter() method, but I have to call it from a listener, is that possible?
Answer: You would want to handle the touch events on the UI in someway like the answer in this post.
Comment: Thats great! you can always upvote and accept the answer of your question in order to help other people have the same issue.


Cucumber+Devise routing error

Question: having trouble with testing devise sign up on Cucumber. After "Sign Up" click
it shows
uninitialized constant User::ArticlesController (ActionController::RoutingError)
I suppose that's because right after Sign up, devise redirects logged user to Articles page and but it's not under namespace User. Because I test user it put everything under this namespace.
Answer: This Devise howto says you can route to something not under the User namespace by naming a user_route path:
match 'my/dashboard' => 'my/dashboard#index', :as => 'user_root'

So it sounds like you can do something like:
match 'articles' => 'articles#index', :as => 'user_root'

Cucumber+Devise routing error


Expressão regular com terminação especifica trazer 3 primeiros caracteres

Question: Estou tentando faz uma expressão regular no Oracle com o seguinte requisito:

Terminar com uma letra especifica, caso tenha essa letra no meio não buscar.
Retornar os 3 primeiros dígitos da string.

Para resolver o primeiro problema posso usar:
a\b

O "a" sendo a letra, o \b para pegar uma posição de borda após a letra.
Para resolver o segundo problema, ou seja, retornar os 3 primeiros digitos:
^(...){1,1}

Agora como faço para juntar as duas condições? Ou o jeito que estou fazendo não daria certo?
Exemplos, que terminam como a letra "a", e preciso que retorne os 3 primeiros:

anhanguera
problema
pergunta
Answer: Estava pensando em uma unica expressão, mas não preciso, pois preciso filtrar todos que termine com a letra que quero, e mostrar os 3 primeiros caracteres, ficando assim o script:
SELECT regexp_substr(t.string,'^(...){1,1}')
  FROM tabela t
 WHERE regexp_like(t.string,'A$')

Tiver que mudar o a\b para A$, pois o Oracle não reconhece. Dicas e sugestões são sempre bem vindas.
Utilizei a documentação para me ajudar:
Using Regular Expressions With Oracle Database
Comment: OBS.: `{1,1}` não esta fazendo nada, pois por *default* ele vai capturar 1 vez, e como sua repetição esta limitado a mínimo 1 máximo 1, o efeito é o mesmo ficando apenas `^(...)` [REGEX101](https://regex101.com/r/RoQE1n/1)
Comment: Obrigado Guilherme
Answer: A abstração que você mostrou em sua própria resposta esta correta, mas vejamos como seria a REGEX por completo.
(\S{3})\S*?m\b
Explicação
Eu posso dividir essa REGEX em 3 partes :

(\S{3}) - Captura 3 caracteres, que não sejam de espaçamento. veja mais.
\S*? - Captura infinitos caracteres, que não sejam de espaçamento, mas o mínimo necessário. veja mais.
m\b - Como você mesmo disse, delimita a fronteira.

REGEX101
Comment: Obrigado Guilherme, a expressão no [regex101](http://www.regex101.com) mostra no lado direito o primeiro grupo e o full match,  no [regexr](http://www.regexr.com/) retorna o full match.
Comment: @David os links estão com valores padrões, teria de salvar o para lincar, o regex101 basta apertar `ctrl+s`.  Sobre a questão de não mostrar o grupo, pode ser da ferramenta.


Location Updates in Background Android 10

Question: i have worked with https://github.com/android/location-samples  (pending intent one)and everythink works great for old device (level 24) but the background service doesn't work on android 10.
Do you have any ideas why is that so?
Answer: The reason is Background Execution Limits on the all android version that have API level 26 or greater.
In order to provide user more better battery life and performance. Google started restrictions. now if application is not foreground then background service will not work. you have to make service as a foreground service that will always notify user that your app is running in background.


Show that the circle represented by arc b is not a rectract of the Klein Bottle.

Question: You tried to solve the following exercise, but the truth is I do not have many ideas, can I help you solve it please?

The figures of the exercise $ 12.12 $ are:

As for the suggestion,
Answer: Let $r:X\to A$ be the retract which induces an epimorphism $r_*:\pi_1(X,x_0)\to\pi_1(A,x_0)$ and let $i:A\to X$ be the inclusion which induces an monomorphism $i_*\pi_1(A,x_0)\to \pi_1(X,x_0)$. Then, you can apply the first isomorphism theorem to conclude that $\pi_1(A,x_0)\cong \pi_1(X,x_0)/ker(r_*)$ (isomorphic to a quotient). So if you rewrite the RHS of the expression,
$$\pi_1(A)\times\pi_1(X)/\pi_1(A)\cong\pi_1(A)\times\pi_1(X)/(\pi_1(X)/ker(r_*))\cong\pi_1(A)\times ker(r_*)$$
Then it's pure algebraic process, see here or here (where you need to use the condition that $\pi_1(A)$ is normal).

To calculate the fundamental group for klein bottle ($K$) using the method in you book would be the following.
Choose an open square called $U$, homeomorphic with an open disk which is simply connected, just like the follwing picture.

Then choose $V=K\setminus I^2$ which is equivalent to this bigger square minus a square smaller than $U$ so that $U\cap V\neq\varnothing$.
it's easy to see that $\pi_1(U,x_0)\cong\{1\}$. For $V$, it can be deformation retract to the square (outer boundary), so $\pi_1(V,x_0)\cong\Bbb{Z}\times\Bbb{Z}$
It's easy to see that $\pi_1(U\cap V,x_0)\cong\Bbb{Z}$ since $U\cap V\simeq S^1$. Let $j:\pi_1(U\cap V)\to \pi_1(V)$, and then $N=\text{Im }j_*=<aba^{-1}b>$ and hence $\pi_1(K,x_0)\cong \pi_1(V,x_0)/N=<a,b|aba^{-1}b=1>$ by applying Van Kampen's Thm.

To show $K$ doesn't retract onto $b$ (call the space $B$), we, first, try to show it's normal:
$$\pi_1(B)=<b>=\{b^m|m\in\Bbb{Z}\}\cong\Bbb{Z}$$
and
$$aba^{-1}b=1\implies aba^{-1}=b^{-1}\in \pi_1(B)$$
which implies $\pi_1(B)$ is normal.
Next, assume $K$ does retract onto $b$ then $\pi_1(X)\cong\Bbb{Z}(b)\times(\Bbb{Z}^2(a,b)/aba^{-1}b)/\Bbb{Z}(b)$, but we reach to a contradiction since the RHS is the product of a group with 1 generator and an infinite cyclic group.


How can i assign context path dynamically in angularjs

Question: I want to assign context path dynamically in angularjs.For example instead of giving url:'op/services/.....' in the below code i want to assign the path dynamically like we do in jsp "url:'request.getContextPath()/services/...'".Since i cant use request.getContextPath() in angularjs which function i should use instead.I dont want to hardcode it because my project requirement is in such a way that the context path might vary for different users..
<code>$http({
            'url' : '/op/services/saveTemplate',
            'method' : 'GET',
            'headers': {'Content-Type' : 'application/json'},
            'params' : \\something
            }).success(function(data){
                    //some function
             });
</code>
In jsp we use request.getContextPath() but i am not sure which function i should use in angularjs.I searched the net but couldnt find anything...
Comment: you are being mean and i think you dont understand the issue....it is indeed wrapped inside a function and i just want to implement the url in my code like url : '<%=request.getContextPath()%>/services...' since i cant use request.getContextPath in angularjs i want to know if there is any other way to implement it...
Answer: The best way to do what you want is to either fetch the value you need with an ajax api call,or bootstrap the url in a script tag and use a global variable to refererence the url
like
<code><script>
window.myUrl ="<%=somejsp%>";
</script>
</code>
before loading any other script in your page.


Custom Editors in an Ext.js Grid

Question: So this is my first time posting here but I'm more or less stumped. Basically what I have is an ext grid that loads a bunch of data. Among these columns are all these date fields. Start, Finish, Etc. I'm trying to create a date picker to edit these columns. I've experimented with the different ext component editors and I was able to hack together something that mostly worked but what I would really prefer is a way to use my own custom date picker or even better a third party solution like the JQuery UI date picker.
Neither extending nor overriding the editor seemed to do the trick. I'm not so much looking for code but more whether this is even possible with ext and if so maybe to be pointed in the right direction. So has anyone ran into a similar problem? Thanks in advance.
Comment: Is there any reason you're not using the built in Ext date picker?
Comment: its something mandated from the top down. they just want ext for the grid and store. Where possible they would prefer to use there own custom components or at least ones they choose because ext doesn't really work all that well with well anything
Comment: I'd say you're going to have a pretty hard time of it. Ext doesn't really "play" with other frameworks because it's for building apps, it's not in a space like jquery where you take bits and pieces and mash them all together.
Answer: It seems to me that it would be fairly straight forward to extend Ext.form.field.Picker and use the jQuery date picker as the picker part.  I've wrapped the FCK editor in an Ext component and it was very easy to do.  Picker involves a few more moving parts, but I think it's worth a try.
That being said, the idea of picking a few parts of ExtJS to use in a non-Ext app and then trying to marry other things into Ext is going to be painful.  I strongly advise fully embracing ExtJS and then choosing very carefully where you stray away.  Another approach might be to use a different grid system (sorry Evan) that plays nicer with jQuery.

Custom Editors in an Ext.js Grid


Why does a query string return a 404 error?

Question: I recently upgraded from Drupal 8 to Drupal 9 and noticed a problem that occurs when the URL has a query string. For example for the following URL Drupal throws a 404 page not found.
https://example.com/2021/07/how-drive-cruise-ship&ct=ga&cd=EAEYACoTMzczMDU5MTUxNjcwNDQyMzUxNzIcN2RiZjYwOGY4MzE2NmM3OTpjby51azplbjpHQg&usg=AFQjCNEa2-Hx3zqnQ59AJFnde_ORtLTvgA
Answer: The query string is badly formatted.  It needs a ?:
https://example.com/2021/07/how-drive-cruise-ship?&ct=ga&cd=EAEYACoTMzczMDU5MTUxNjcwNDQyMzUxNzIcN2RiZjYwOGY4MzE2NmM3OTpjby51azplbjpHQg&usg=AFQjCNEa2-Hx3zqnQ59AJFnde_ORtLTvgA


Why does changing css for a single component affect all other components?

Question: Goal: Have CSS only affect the component its on, not others. I only wanted to affect my dropdown, not other text entry fields:

Background/Problem: I understand why it would affect multiple items on the same page (mat-form-field's). But don't understand why it would affect OTHER pages. I looked into it but still unsure.
What I tried:
For example, I originally had:
::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
    height: 40px !important
}

::ng-deep .mat-form-field-infix {
    padding-top: 1px !important;
    padding-bottom: 2px !important;
}

But it was affecting the spacing of all form-fields on the page, so I edited it to be:
::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
    height: 40px !important
}

::ng-deep .mat-form-field-appearance-outline .mat-form-field-infix {
    padding-top: 1px !important;
    padding-bottom: 2px !important;
}

Other unchanged CSS:
.title-container {
    position: relative;
    margin-top: 8px;
}

.language-field {
    position: absolute;
    right: 0;
    top: 0;
    margin-top: -16px;
    width: 115px;
    height: 20px !important;
}

This fixed that, but it is still odd to me that changing something on login.component.css would affect all other pages in the site such as profile.component.css
Here is associated HTML for login.component:

    <mat-card-title class="text-center">
        Please Sign In
    </mat-card-title>

    <form [formGroup]="_siteForm">
        <mat-form-field class="language-field" appearance="outline">
            <mat-select (selectionChange)="changeSite($event)" [value]="languages[i].value">
                <mat-option *ngFor="let language of languages" [value]="language.value">
                    {{language.viewValue}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </form>

When I researched into this:
I found some SO articles (such as Angular 2+ : Component style keeps affecting other components) mentioning using encapsulation: ViewEncapsulation
However, when looking through the site, I don't see this used anywhere, however there is css on different components that all mention mat-form-field but with different values. This seems like it would indicate that encapsulation is not needed.
In regular HTML I did not use to have these problems, but am confused on how this is working in Angular. Does this have something to do with Angular being a SPA?
Comment: Note that `::ng-deep` is [deprecated](https://angular.io/guide/deprecations), but with no timeline as to when it will be removed.
Answer: I think it's your ::ng-deep, remove that.
Then use a specific class name and declare it in that components css file.
e.g. in home.component.css
.mat-form-field-flex {
    height: 40px !important
}

Comment: Thanks Lilly_Code. It sounds like you are saying: .myclass {
    padding-top: 1px !important;
    padding-bottom: 2px !important;
}

But would html still remain

or
Comment: I tried adding these to the "language-field" class from the html but it did not work. I Also tried removing the ngdeep but then it removed the styles (box was in a weird place, weird size)
Answer: It's slightly hard to grasp what you're trying to show here without a code snippet with that CSS.
But if it's breaking Angular's view encapsulation which all components have by default, I'd be almost positive it's because you're using !important selectors, these should really only be used in the rarest of situations -  https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
The reason for this is because using !important will break the css specificity Angular uses to encapsulate it's components.
Css specificity works like so.
Inline styles are worth 1000pts
Id's are worth 100pts
Classes are worth 10pts
Elements are worth 1pt
The !important is essentially worth infinite points it always takes precedence.
div>p>.className = 12pts
div>p>#classname = 102pts
This means that any styles in
div>p>#classname
will take priority over any styles in
div>p>.classname
I won't go into details here about how Angular achieves there encapsulation with this technique, if your interested here's a good article - https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html
Answer: Ensure you haven't set encapsulation to ViewEncapsulation.None
@Component({
  selector: "my-component",
  templateUrl: "./my-component.html",
  styleUrls: ["./my-component.scss"],
  encapsulation: ViewEncapsulation.None
})

Answer: I also got the same problem. You are using ::ng-deep. ::ng-deep is a global level element it affect all the component. So, use :host as prefix. :host will contain the ::ng-deep in the same component. It won't allow it to affect other components. Use this :host ::ng-deep. Replace all ::ng-deep with :host ::ng-deep.


What are the modal characteristics of major modes?

Question: This question comes out of two recent questions and answers about modal music:

In what way is music considered to be in a mode when accidentals seemingly contradict the mode?
What are modes in the real world?

@Athanasius gave very helpful answers, especially explaining that modes aren't fixed scales, but more like melodic conventions or archetypes, and especially important with flexible treatment of certain degrees of the (scale/mode/key.)
The explanation in What are modes in the real world? by comparison to minor mode conventions - like the treatment of the leading tone - made clear how "mode" is more about melodic processes.
That most obviously translates to being in Dorian mode, where the third is minor and the sixth is often minor and the seventh is raised for a leading tone. Basically, old Dorian mode is modern minor key. Aeolian wasn't a name used historically and to the extent that someone would use the name - or natural minor - in modern times the "modal" handling is still essentially the same as Dorian or modern minor key.
Phrygian is unique compared to the other minor modes. It has a minor third and sixth and its leading tone is the half step above the tonic. Seemingly it doesn't need adjustments of tones like Dorian/minor mode. In terms of melodic process being in Phrygian mode would seem to mean not needing to raise/lower tones. It's more purely diatonic.
If that description of minor mode is more or less accurate (I hope it is,) my question is: what are the features of being in the major modes?
From the earlier questions I understand that Lydian was the historic name and Ionian was never used. Lydian mode frequently lowered the fourth degree from an augmented fourth to a perfect fourth above the tonic. In doing so Lydian and so-called Ionian become roughly the same as modern major key.
Is that the primary modal aspect of Lydian?
What happens with Mixolydian beside raising the seventh for a leading tone?
In terms of modern major keys, a raised fourth and lowered seventh are used to tonicize the dominant and subdominant respectively. It's noticeable those are the two variable degrees in Lydian and Mixolydian. Can the two somehow combine to a major mode similar to how minor mode has its own set of variable degrees? My first thought it "no", because #^4 and b^7 change the tonic, whereas variable ^6 and ^7 in minor don't change the tonic. But that may be a hasty conclusion from a largely modern, harmonic perspective.
I fear I'm just repeating the earlier discussions in the two old questions. Are Lydian, so-called Ionian, and Mixolydian all really reduced to one major mode?
If the true difference in those modes lies way back in early Chant, and the distinction truly was lost by the times of early polyphony, that basic knowledge is helpful too.
Comment: Phrygian's leading note is a semitone *above* the tonic? What's the definition of a 'leading note'? The penultimate in a scale, as long as it's only a semitone below the tonic? Does that mean that a semitone *above* the tonic can also be termed 'leading note'? That's news to me.
Comment: If I'd understood it, I wouldn't be asking. Nitpicking doesn't have anything to do with it. There would be no point, so I didn't.
Comment: Maybe I misread your comment's tone, but "that's news to me" seems sarcastic. I couldn't tell if you were trolling me, to make me go out and quote first species counterpoint.
Comment: @Tim https://books.google.com/books?id=6NgnF-xFsOcC&pg=PA18&dq=phrygian+leading+tone&hl=en&newbks=1&newbks_redir=0&ppis=_e&sa=X&ved=2ahUKEwiEvZC5mc_nAhUDqlkKHdeMDjUQ6AEwAXoECAAQAg#v=onepage&q=phrygian%20leading%20tone&f=false
Comment: @Tim https://books.google.com/books?id=7IP0Jo9Dr9QC&pg=PA10&dq=phrygian+leading+tone&hl=en&newbks=1&newbks_redir=0&ppis=_e&sa=X&ved=2ahUKEwiEvZC5mc_nAhUDqlkKHdeMDjUQ6AEwAHoECAMQAg#v=onepage&q=phrygian%20leading%20tone&f=false
Comment: The point is just that the clausula vera is sort of inverted in Phrygian with the half step above the tonic rather than under it. As far as _definitions_ go, the question is very much about _history_ and the terminology runs across centuries and various languages. What's the point of nitpicking definitions when the meaning is understood in context?
Answer: I don't know that there's a definite answer to this question, but I'll offer a few thoughts.
If we go back to the days of monophonic chant, as you said, Lydian was a scale that was like the modern major scale, with a flexible fourth degree (natural or sharp).  Mixolydian was like the modern major scale, with a lowered seventh scale degree.  (Note that Mixolydian chants rarely -- but still occasionally -- employed B♭, but when they did so, they could also be thought of as a "transposed Dorian."  I mention this because there was really no strict delineation between "major modes" and "minor modes" in chant, as this division and grouping into two polarized major/minor categories didn't become clear until the early 1600s.)
To the extent that a "major mode" emerged in 15th and 16th century polyphony, it had the features you discuss.  It typically had the major third above the final/tonic.  It sometimes had a flexible fourth and/or seventh scale degree.  The more frequent occurrence of E♭ in 16th century music allowed an F-final piece to perhaps dabble in the possibility of both ♯4 and ♭7 in the same piece, though that was rare.  Sharps in general were rare and still regarded as musica ficta until later in the 16th century.  Once they became more standard, and "chromatic" ideas reemerged with the new emphasis on rediscovered Greek theory, all sorts of accidentals started happening, leading to wide-ranging harmonies.  (See, for example, the works of Gesualdo, or -- on a less extreme scale -- the Prophetiae Sybillarum of Lassus.)
But if we back up a few decades and look at the emerging sense of a cluster of "major" polyphonic modes in the 1500s, I'd say your description is pretty much on target.  A lot of works will oscillate back and forth between a raised 7th degree as leading tone and a lowered one employed elsewhere (not at cadences), effectively the "Mixolydian" gesture.  I don't think this gesture ever truly went away in popular music; it clearly survived in various religious and gospel styles and is present in modern popular music that employs ♭VII in various contexts. A lot of these bear striking similarities to many standard "major mode" works of the 16th and 17th centuries.
The ♯4, on the other hand,  was transformed earlier into more of a leading tone to scale degree 5.  It's more likely to occur in cadential gestures to that note in 16th-century polyphony, rather than as a melodic or coloristic alteration.  That's not to say it doesn't happen, but my sense is that ♯4 gradually declined in favor of the natural 4 in the emerging "major mode," and the harmonies it supported gradually turned into modulations to the dominant.  Of course, those eventually became the progenitors of the modulation to V that was standard in common-practice works.
There's part of me that would really like to think that ♭7 in Mixolydian was also the ancestor of modulations to IV.  I think in some sense it is, but I think more explicitly it's the ancestor of the sort of "turn to IV" that frequently occurs near the close of a work in baroque and classical styles, where you'll start off a piece in I, go to V, then go back to I, and then the final phrase or two will have a ♭7 to hint at V/IV before the piece comes to rest.  That sort of "plagal" turn toward IV has predecessors in final phrases dating back to the late renaissance, where perhaps (?) it was a remnant of the old Mixolydian inflections.
These last few paragraphs are kind of speculative, but if you take a hard look at Bach, one of the defining characteristics of "being in major" was generally a modulation to V.  And while not as required, the little "turn to IV" near the end is quite common once you start looking for it.
To come to your articulation of this:

In terms of modern major keys, a raised fourth and lowered seventh are
  used to tonicize the dominant and subdominant respectively. It's
  noticeable those are the two variable degrees in Lydian and
  Mixolydian. Can the two somehow combine to a major mode similar to how
  minor mode has its own set of variable degrees? My first thought it
  "no", because #^4 and b^7 change the tonic, whereas variable ^6 and ^7
  in minor don't change the tonic. But that may be a hasty conclusion
  from a largely modern, harmonic perspective.

I agree with your last sentence -- you're thinking about this a bit too much from a modern harmonic perspective.  More specifically, I think you're approaching it too much from the lens of diatonicism, which was not the world that Bach or Handel  lived in.  They weren't taught theory with diatonic major scales as the basis of harmony for a year before someone allowed them to write a chromatic note (as many music undergrads are taught today).  Accidentals like ♯4 and ♭7 were fundamentally a part of what "major mode" meant for them.  Those were necessary and expected accidentals that were to be composed in at appropriate points in a piece, similar to how renaissance musicians understood that musica ficta was necessary to introduce a sharpened leading tone at a cadence.
So yes, I myself have frequently noted the fact that the ♯4 and ♭7 "modal inflections" seem to have survived as modulatory inflections in common practice music.  There's more to the story, to be sure, but I don't think it's wrong to think of them as aspects of the "major mode" that were gradually transformed into harmonic/tonal/key elements.
I'm not sure if that answers your question.  One last thing:

If the true difference in those modes lies way back in early Chant,
  and the distinction truly was lost by the times of early polyphony,
  that basic knowledge is helpful too.

It's really hard to talk about any "true difference" among modes, as modes are a moving target.  Keep in mind that the medieval "church modes" existed in various forms for roughly a millennium before they completely gave way to the major/minor system.  There was a lot of change and development over that time.  (This is a common problem with thinking about the past, where the farther back in time, the slower we tend to think of change happening.  But lots happened over the centuries, which was a much longer time for medieval and renaissance music than the interval between Bach and us.)
Thus, it's hard to speak of what was "truly" Mixolydian, as understanding of that mode in the 16th century was different from the first tetrardus modal concepts in the 9th century.  If you really want to delve into this, I'd strongly recommend starting with the "Mode" article in the New Grove Dictionary, written by Harold Powers.  It's quite long for an encyclopedia article, but it's about as concise an introduction to the manifold versions and concepts of "mode" that existed over time as you might be able to find.
Comment: Sorry for the late answer accept! I thought I had already done it. Your answers to several of my questions have been very informative!


Why is this presupposition necessary? (set)

Question: Let $U_i$ be subspaces of a vector-space V.
If $ U_1 \subseteq U_3 $ then follows: $U_1 + (U_2 \cap U_3) = (U_1 + U_2) \cap U_3$.
I have already proven this equality.
I nood have to show why the presupposition $U_1 \subseteq U_3$ is necessary by giving a few examples.
I want to give an example for $V = \mathbb{R}$ and/or $V = \mathbb{R}^2$
So I wanted to choose some subspaces, well in the first case I only have two options, right?: $U_i = \{0\}$ or $U_i = \mathbb{R}$.
Can you please help my finding some great examples?
Answer: In $\mathbb R^3$ Take $U_3$ the $xy$-plane and $U_2$ the $x$-axis and $U_1$ the $z$-axis then:
$ U_1 + (U_2 \cap U_3)$ is the $xz$-plane and  $(U_1 + U_2) \cap U_3=U_2$ and they are different.
Answer: Anytime you have $dim(U_1)=n>m=dim(U_3)$, $U_1 + (U_2 \cap U_3)$ will have dimension at least $n$, and $(U_1 + U_2) \cap U_3$ will have dimension at most $m$.
Answer: In $\mathbb R^2$, consider any three distinct one-dimensional subspaces. Then $U_1+(U_2\cap U_3)=U_1$ whereas $(U_1+U_2)\cap U_3= U_3$.


After implementing hook_node_access, how to stop node from appearing in view?

Question: In Drupal 8, I implemented a hook_node_access function in my module to control access for a certain role under certain conditions and it works fine.
However, all of that content type are still shown on a view when the user views it. This is expected behavior according to the documentation:

In node listings (lists of nodes generated from a select query, such as the default home page at path 'node', an RSS feed, a recent content block, etc.), ... hook_node_access() is not called on each node for performance reasons and for proper functioning of the pager system. When adding a node listing to your module, be sure to use an entity query, which will add a tag of "node_access". This will allow modules dealing with node access to ensure only nodes to which the user has access are retrieved, through the use of hook_query_TAG_alter(). See the Entity API topic for more information on entity queries.

(Link)
I understand why the view does not check each individual content, but I do not understand what this documentation is asking me to do to fix that. The documentation for hook_query_TAG_alter and on entity queries is not very helpful either.
How do I ensure that only items of this content type that the current user has view access to are shown in a view?
Comment: Does this answer your question? [Views Search Ignoring Custom Node Access permissions](https://drupal.stackexchange.com/questions/52756/views-search-ignoring-custom-node-access-permissions)
Answer: having run into the same problem as you I hope I can save you a headache.
Depending on the amount of results you have I can provide 2 ways to tackle this:
1. Works when you don't need pagination
HOOK_views_post_execute. This will have the rows in the variable. In here you can check the access and unset() the rows not allowed.
2. Works when you need pagination
HOOK_views_query_alter. I've used this solution for a view I needed myself with around 10000 results. I do a custom permissions check based on the user and the groups they are part of. Baed on this I generate a list of ID's of nodes they user is allowed to see. I add these ID's as an "IN" query to the view:
$cond["field"] = "media_field_data.mid";
$cond["operator"] = "IN";
$query->addWhere('1', $cond["field"], $mids, $cond["operator"]);

Where $mids has all the allowed Mids in there.
Hope this helps you get along!
Answer: I had the same issue when using a custom hook_ENTITY_TYPE_access
... just putting an example here to save people time:
/**
 * Implements hook_views_post_execute().
*/
function MODULE_views_post_execute(ViewExecutable $view) {
  if ($view->id() == 'view_name') {
   $result = $view->result;
   $account = $view->getUser();
   $user = \Drupal::entityTypeManager()->getStorage('user')->load($account->id());
   $filter_results = [];
   foreach ($result as $key => $value) {
     $entity = $value->_entity;
       /// opp can be create, view, delete, update.
       if ($entity->access('view', $user) == TRUE) {
        $filter_results[$key] = $value;
     }
   }
   $view->result = $filter_results;
  }
 }


How to create soap service using GET method

Question: I'm beginner to the soap web service. When I create soap service don't think about That service is POST or GET .But when we create REST service we initialize that service is POST or GET.
I created soap web service.Here is my code
<code>@WebService(targetNamespace = "http://service.test.hameedia.com/", portName = "HameediaTestServicePort", serviceName = "HameediaTestServiceService")

public class SoapServiceTest{

     public String details(String name){
        //some thing in here
     }
}
</code>
But in here we didn't initialize this is POST or GET .But console show this is POST method.My question is

Is soap web services default method type POST

If is it not

How to create soap web service with GET method

I get some idea from this.But I'm not clear with my question.If you have any idea about this please share.
Comment: Due to the nature and complexity of the content it is POST only. With GET you can only encode the URL which isn't suitable for SOAP. So although you might be able to get it to work for simple calls (does that exist in SOAP?) generally it will never work.
Comment: Thank you M.Deinum
Answer:
SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification.

SOAP is not depended upon HTTP and HTTP Method(s), SOAP can extend HTTP for XML messaging.
You can call SOAP Web Service over HTTP and you have to use POST method only because of complex nature of the SOAP Request.
Ref : https://www.tutorialspoint.com/soap/what_is_soap.htm
Comment: Thank you Avinash. What is that complex nature. Do you have any idea or some reference.
Comment: Please search google and understand SOAP. SOAP cannot be compared to Rest API directly. You will automatically understand what complexcity I am talking about.
Comment: Thank you. Finally I got some idea about that using this.https://www.ibm.com/developerworks/library/x-tipgetr/


Recommendations about the exponential function

Question: I am studying differential equations and I am very surprised by how omnipresent the exponential function is. It pops up everywhere, but there isn't usually a lot of detail provided in introductory textbooks about how the solutions come up and why the exponential function has so much importance. One thing I find fascinating is how the exponential function has the characteristic that it is the same as its slope. I'd like to know more about it so that I can understand why it's so important.
I guess the main problem is that this would probably require going into some real analysis. As I said, I have some knowledge of ODEs, calculus and linear algebra (and I have worked a little bit with proofs). So I would be very grateful if I could get some recommendations from you to get deeper into the topic of exponential functions, perhaps analysis more broadly if that is required.
Comment: "One thing I find fascinating is how the exponential function has the characteristic that it is the same as its slope." That's a big part of why it shows up in differential equations so much.
Comment: Closely related to $f(x)=e^x$ satisfying the nice ODE $f'=f$ is the simplicity of its [power series](https://en.wikipedia.org/wiki/Euler%27s_formula). You may want to study Taylor expansions/series for that reason. To know the other formula $e^x=\lim_{n\to\infty}(1+x/n)^n$ is a must as well.
Comment: Any physical model which has the rate of change of a quantity depending on the amount of that quantity generates an exponential solution. So nuclear decay rate, Newton's law of cooling, charge across a capacitor, pressure in a balloon ...
Comment: @Paul Compound interest
Answer: There is a completely satisfying abstract explanation of why the exponential function shows up so much but it requires some familiarity with linear algebra. Once you understand that language, the explanation is: $e^{\lambda x}$ is the unique (up to scale) eigenvector for the differentiation operator $\frac{d}{dx}$ with eigenvalue $\lambda$. This says concretely that $e^{\lambda x}$ is the unique (up to scale) solution of
$$\frac{d}{dx} y(x) = \lambda y(x).$$
This turns out to completely explain the importance of exponentials for solving linear homogeneous constant-coefficient ODEs; abstractly and in one sentence, it's because exponentials diagonalize any differential operator which is a polynomial in $\frac{d}{dx}$. But one has to know quite a lot of linear algebra to make sense of this. For that you can consult any textbook on linear algebra; Axler's Linear Algebra Done Right might be a good place to start.
Comment: There is also a generalization where $\lambda$ is replaced by a matrix which is important e.g. for studying the behavior of an autonomous differential equation $y' = F(y)$ at a fixed point and classifying equilibria into stable vs. unstable and so forth. I suppose the chain rule + the basic $\frac{d}{dx} e^x = e^x$ is the most general thing one can say here but the eigenvector stuff above suffices for the linear homogeneous constant-coefficient stuff which I assume is what the OP is referring to.


Como procurar uma palavra em 10 tabelas no MySQL

Question: Estou a fazer um formulário para uma pesquisa, e ao procurar por algo, pretendo que retorne vários valores de varias tabelas que existem.
Como tal, gostaria de saber a forma mais fácil de fazer uma query, na qual não seja muito pesada e que consiga ler todas as tabelas com vários campos diferentes.
Comment: Alguma resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: Uma forma é utilizar a cláusula UNION e juntar os resultados de pesquisa:
SELECT 'TABELA 1' AS origem
       t1.campo1,
       t1.campo2
  FROM tabela1 t1
 WHERE t1.campo1 like '%texto%'
    OR t1.campo2 like '%texto%'
UNION
SELECT 'TABELA 2' AS origem
       t2.campo1,
       t2.campo2
  FROM tabela2 t2
 WHERE t2.campo1 like '%texto%'
    OR t2.campo2 like '%texto%'
...
UNION
SELECT 'TABELA 10' AS origem
       t10.campo1,
       t10.campo2
  FROM tabela3 t10
 WHERE t10.campo1 like '%texto%'
    OR t10.campo2 like '%texto%'