If someone can sing a melody, why can they not also recognize the intervals within that melody?

Question: Surely everyone who struggles with relative pitch already has in-built relative pitch, so why is it so hard to actually recognise intervals?
What I mean is from a child I (and most other people I imagine) could sing a tune they had just heard. They might sing it in the wrong key but they would still sing it correctly in a key. To do this you surely need to be able to know the intervals in the tune you have just heard and then replay it back with your voice.
However, ask me explicitly to say whether an interval is a half tone or whole tone and I will struggle. How can this be? How can I easy sing a song whose first two notes are a tone apart yet not be able to recognise a tone in isolation?
Another way of phrasing this question is, why can most people learn to identify intervals easily using reference songs for each interval (took me less than 48 hours to do it within 95% accuracy) but yet actually memorising the intervals in isolation takes months (years in my case).
I realise that this question is not just about music theory but neuroscience and that it may not be wholly understood but I am interested to read your views.
Please note that this question is not about any actual instrument. A good answer will also EITHER explain why I appear to have memorised intervals since I can sing tunes well yet not recognise an interval in isolation OR reveal why my being able to sing tunes does not imply that I have internalised intervals. I write this because there are so many answers on the internet which superficially answer this question without getting to the heart of the query
Comment: Interesting, I think this is analogous to an athlete throwing a ball to a teammate. A child can quickly learn to throw accurately to someone 10 m away, 20 m away, 30 m away, etc.; but being able to say how far away that teammate is requires additional knowledge about length units and considerable practice and experience.
Comment: I tried to make the title more specific; feel free to edit or rollback as needed!
Comment: If someone can jog, why can they not also recognize the muscles used in jogging?
Comment: I mean, this is partly tongue in cheek but can a tape recorder understand what an interval is? It is entirely possible to reproduce a sound without understanding abstractly how it was designed.
Comment: Your question immediately made me think of [this video](https://www.ted.com/talks/bobby_mcferrin_watch_me_play_the_audience) which supports your claim. The presenter teaches the audience two notes, which they repeat, but then (at 0:43) jumps to the next note and the audience finds the right note (even better at the end of the video), showing that people do intuitively understand intervals and scales, even if not consciously (since I doubt any significant percentage of the audience would be able to even tell you what an interval precisely is, let alone recognize or measure one).
Comment: Experiments show that chickens can count and do arithmetic with small numbers. However, they aren't able to attach labels to numbers or communicate them to other chickens.
Comment: People can identify and reproduce plenty of sounds they cannot name or describe.  Consider R2D2, BB8, and Chewbacca for good measure
Comment: I can phonetically recite much of the Huttese spoken by Greedo in the cantina in *Star Wars*, but without the subtitles, I would have no idea. what he is saying. Reproducing sounds and understanding those sounds are two different things.
Comment: Three year old children can also produce grammatical sentences such as "I'm a fast biker" without knowing concepts such as noun, verb, adjective, subject, predicate, object, contraction, or suffix of agency.
Comment: I think this is a very good question :) but I'd add another layer on this: when I play with apps to recognize intervals, I usually make a bunch of mistakes, but 10-15 min in, I get pretty good. The next day.. same story, so somehow I'm not learning. When I hear an interval, finding it on a guitar takes place at some intuitive level and I have good accuracy. Not sure why the difference.
Comment: I asked a parallel question to this: https://music.stackexchange.com/questions/100757/finding-intervals-on-an-instrument-vs-naming-them
Comment: If you sing a song, you probably can't tell at which frequency you sing either.
Answer: I think the answer boils down to what you mean by "knowing" the intervals.

To do this [sing a tune back] you surely need to be able to know the intervals in the tune you have just heard and then replay it back with your voice.

I don't think "knowing" these intervals in order to sing something back means you know if an interval is, e.g., a major or a minor third. When you sing something, you're just mimicking something you already know. There's not necessarily any true "knowledge" here; just ask the countless opera singers that sing for hours in another language without actually knowing how to speak it. They can reproduce the sounds, but they don't fully understand the meaning behind them. The same is true here.
But there's an added wrinkle: intervallic ear training is problematic because it's teaching you intervals within a very specific functional context. People use "Somewhere Over the Rainbow" as an ascending octave, but it's really an ascending octave from scale-degree 1 up to another scale-degree 1. If you're singing scale-degree 3, thinking of "Somewhere Over the Rainbow" won't always be helpful; you may well sing up to scale-degree 1 (a minor sixth), not an octave up to scale-degree 3.
As another example, people can know what a major second is (it begins "Happy Birthday"), but they may only be able to recognize it accurately when it's between scale-degrees 5 and 6 in major (as it is in that tune). They'll likely have some problems hearing—and definitely creating without prior reference—that same major second between scale-degrees 3 and ♯4.
Comment: @awelotta: I don't read this answer is saying "we don't memorise melodies X way, we memorise them Y way instead".  I read this answer as saying "there are many different ways we can memorise a melody, so being able to sing a melody doesn't imply capability in any one specific approach".
Comment: Mimicking is easy - birds do it all the time.  Does that mean birds instinctively have a full understanding of basic music theory?  Hardly.
Comment: So basically, we don't necessarily memorize relative pitch, but tonality, according to this explanation. Does that suggest that internalizing melodies from songs with ambiguous tonality or songs that are deliberately atonal would aid intervallic relative pitch?
Comment: "problems hearing...that same major second between scale-degrees 3 and ♯4" – right. Moreover, they might even feel that the minor second between 3 and ♮4 sounds more similar to the major second between 5 and 6, simply because it fits more natural without that Lydian ♯4!
Answer: I'm going to take this one from the perspective of someone who's long earned a living by being able to sing well, yet has an abysmal pitch recollection without at least some cues to it…
I suppose I also ought to mention that even though I've been doing this nearly 50 years now, I have no formal training to speak of.
Part of singing a tune you already know is that, either consciously or subconsciously, you are also hearing the chord structure that the tune went with. This is a massive 'coat hanger/scaffolding' that holds up the entire structure & gives it recognisable form.
For a song I know well & have performed often I can pretty much hit the right key from the start with no external reference, just because my voice knows where it is even if my brain doesn't, & not drift for the entire song.
Once I nail it, I've got it.
Any tune in isolation, with no chord structure, is going to be harder to remember, especially if it's very chromatic - harder intervals, harder to learn in isolation. Even a song I've heard a lot, but is outside my repertoire, so I'm having to try to pull together this invisible chord sequence without already knowing it well-enough, can be a challenge in this respect.
As a singer with really tight pitch tolerance, but nothing that could even be called good interval recognition [I can find an interval only by singing a scale & counting] I don't know how the guys who can do this… do this.
If I can't hear or at least manufacture in my head a generic chord structure the melody sits on, I will quickly lose it. I'm stumped, not even a clue where the next note should be.
What a muso-psychologist would make of that, I have no idea ;)
Comment: As someone who's learning Gregorian chant, I don't think that this explanation really holds up; similar for many styles of folk music. It might *help* as a mnemonic with certain melodies but definitely isn't a necessary skeleton.
Comment: @chrylis-cautiouslyoptimistic- well, different genres, different approaches. I (as an instrumentalist) think very much in relation to harmonic functions too, which works great in a rock/blues/pop setting, pretty useful in a classical setting, but indeed tends to be rather counterproductive when I'm playing folk tunes, especially ones that are not derived from central-, western- or southern-European traditions.
Answer: Because our brains don't need to consciously be aware of intervals.
Your question is the same as the following question:

If I draw an X on the ground and ask someone to jump from where they're standing to the marked spot, and if they succeed at doing so, why are they not also able to tell me exactly what distance they've jumped?

Or even more succinctly:

If people can perceive the color aquamarine, why can't they tell me its precise RGB values?

For the jumping example, the visual information of gauging a distance and the physical movement required to jump to it is not mentally processed using numbers or any kind of objectively measurable unit.
Cognitively, we could physically measure the distance, derive the required forced to launch our body in a parabolic trajectory from the origin to the destination, work out how to move our muscles to generate this precise amount of force, and then do it. But our brains have been hardwired to deal with sensory information subconsciously.
For the color example, while theoretically your eyes are perceiving individual RGB values using rods and cones, we cannot consciously parse this information separately. Instead, our brain only receives the aggregated RGB output and only sees the big picture. It isn't really capable of independently observing the alpha channels (i.e. the R, G and B information separately).
Similarly, for your question, auditory information doesn't always get mentally processed using music theory. If every human were required to understand the theory behind the music they make, the field of music theory would only be able to focus on exploring new things (that people cannot yet do until the appropriate theory is invented), rather than defining things that people are already doing (but cannot yet theoretically/analytically express).
It's a fairly recurring thing in life where people are first able to do something, and only then figure out the theory behind it (why they are able to do it, how to do it better, ...)
It's very rare for something (especially something sensory) to be discovered purely theoretically before there has been any physical encounter or application.
Answer: I wondered the same thing! I still can't recognise isolated major thirds and minor thirds well, but I can sing them accurately. I don't know the answer for certain, but maybe these anecdotes can help get us closer to the answer.
Singing intervals from song reference is easier because we are singing relative to a tonic. If the song is C major, singing a G -> B major third is easier than hearing it without a tonic because our brains are hearing the C -> G perfect fifth and the C -> B major seventh. Our familiarity with the major scale helps us here. (This was pure anecdote but after a quick Google apparently it's been researched and researchers found that tonal context DID improve interval recognition for musicians. https://www.frontiersin.org/articles/10.3389/fpsyg.2017.01753/full)
Compare this with exercises where an app will play some intervals, ascending or descending, in some order:

The width of an interval varies with pitch, which adds to confusion. The absolute change in frequency of a major third between C and E is narrower than a minor third between the A and C above, for example.
In regards to the neuroscience you mentioned, one "artifact" of interval recognition exercises I noticed myself falling for is an apparent widening/narrowing depending on frequency change between interval pairs. E.G if I heard a major third from, say, C4 to E4, and then another from G2 to B2, I "felt" the second interval narrower than it was, because it had just descended pitch significantly. Similarly, big ascensions tricked me into thinking they were wider.
I found that exercises which used pure tones (no overtones) were far harder than ones which used piano soundbanks. I also find it much easier to match pitch to human voice than piano).
Comment: Some of this seems speculative, and #1 doesn't make sense to me.
Comment: Hi @Ben, yep I agree it is speculative; I prefaced my answer as such! I'm certainly no expert, just wanted to add my two cents. In regards to point 1 though, that's a mathematical truth. If the width in Hz of a major third from C4 to E4 is X Hz, and the width of a minor third from A4 to C5 is Y Hz, then Y is greater than X.
Answer: I often remember music accurately enough that I can play it back in my head, complete with instrumentation details. This means that, when I sing that song, I pitch-match my singing to the audio clip in my head. I don't necessarily pick up on the intervals I sing.
(This leads to obvious trouble when I'm told to transpose any song that changes keys enough times. In this case, I actually often remember the interval I need to transpose instead of the interval between the note I'm singing and the next or previous note in the song.)
Based on studies of the Levitin Effect, where some people can recognize when music is played in the original or correct key even without musical training, I believe I am far from the only person who remembers music this way. Therefore, I believe that many others, and possibly you, could very well sing songs purely by matching sung notes to memorized audio clips instead of replicating interval chains.
(My experience with interval training with reference tunes, though, is that the tunes actually do lead to quick interval-in-isolation recognition. Ear training for piano exams was particularly cruel like that.)
Answer: My answer is that the solution is: re-formatting our "hard disk". You're correct saying that we have no problem to identify intervals referring to songs, but parallel we need to recognize the intervals by their character of perfect consonance, consonance and dissonance without referring to a song, or integrate both paths to one way of recognition and association.
As long we have to analyze the intervals by references to songs-intervals we are only on the half way. We need more practice and my way is ear training by writing and composing.
So my answer is: Normally we don't have just one approach to identify sounds and chords. The song reference  is not every ones approach. And even if we are able to sing a song in tune not everyone is able to play it. But just find out the intervals on an instrument by trial and error is a good practice.
It may be similar to the grammatical analysis of our mother language. We are able to talk and understand others, but to use our words with content of their etymological meaning we have a long way to go of studying and researching.
Answer: There are many things that we learn to do backwards. Personally, I learned to talk as a young child many years before I learned to spell the words I was speaking. Somehow we seem to be able to perform functions such as things we hear and see happening around us without knowing all the details. I can drive my car without knowing the mechanics involved. I can play my guitar without knowing music theory. And like you, I could sing without knowing a thing about intervals. These are abilities that we have. The things like spelling, mechanics, music theory, and intervals, seem to be our attempt to explain the processes that are taking place in an attempt to advance our understanding of what we are doing. This is of value to some of us and completely worthless to others of us depending on our interests. I apologize for not being able to explain the workings of my brain, I've done no studies in that realm.
Answer: Perhaps I'm getting your question wrong but: Think of it like being able to recognizing colors and knowing the names of said colors. You can know what yellow, red, blue feels like, and can discriminate between each other. If someone shows you a yellow sheet and tells you to choose the crayon that has the same color, you can grab the yellow crayon (you can sing the interval you heard). But if you never managed to memorize that the sheet's yellow color is actually called "yellow", i.e. the name given to that color is "yellow" you can't name it (you can't name the interval). So being able to discriminate between pitches, and knowing the name of said intervals are entirely different things.
Of course, most people's visual / color perception is a lot better than their sound perception. So memorizing colors (associating the certain quality of things you see to names) come easier for most (but not all) people. Memorizing intervals are generally harder for that reason.
Comment: I find the analogy very valid, both are frequencies, even if the tool to perceive them is different, it takes knowledge and learning to be able to tell what is the frequency delta between 2 in both of them
Answer: Great question!
Another phenomenon is that for most people (including me) it is more difficult to tell apart intervals in the high registers, and much easier to identify intervals in their own vocal range.
@Richard and many others gave excellent answers. It has much to do with context. Let me note that for my ear training, I use an app called Functional Ear Trainer, that not only plays intervals, but plays them within a harmonic context.
So, my initial remarks and the explanations make one thing clear: intervals are an abstraction! One specific aspect, disregarding everything else. People who sing songs, sing intervals, but not every sequence of intervals makes up a song. There are much more constraints on the intervals to actually make them a  (pleasant to hear and memorable) song.
Some analogies: You are much more than merely the chemical components you are built of. The computer in front of you is much more than a bunch of metal, plastic and silicon. This is what Aristotle meant with saying The whole is more than the sum of its parts.
I vaguely remember that psychologists confirmed that people could have good domain specific knowledge that they struggle to transfer to a different task, even though that task might be the same on an abstract level. I am sorry, I cannot cite anything since it is almost teen years ago since I studied psychology. But I can give you some keywords for your own research: domain-specific knowledge, expertise, knowledge transfer, problem-solving, cognitive psychology.
Answer: Another issue not yet mentioned is that some melodies, as popularly performed, may include features like slides, bends, or blue notes that don't fit the normal terminology for intervals.  If a singer sings the root, followed briefly by a pitch that's slightly above the major third, but it quickly falls to be closer to a minor third and then its descent slows briefly, before accelerating into a slide back to the root, what interval did the singer perform?  One might be able to accurately mimic a popular performance of a piece but be be unable to determine whether an interval is a major third or a minor third because the interval one is performing might not be either of them, but instead some weird hybrid for which no standard terminology exists.
Answer: Imitation is one thing, analysis another.  You can tell a story without knowing how to spell the words.
Interval recognition is complex.  Pitch, pawn, park.   Each of those words has at least two distinctly different meanings.   A minor 3rd sounds very different whether it's 1 & 3 of a minor triad or 3 & 5 of a major one.


Mostrar um div para cada opção de um dropdown

Question: Tenho que criar um dropdown que mostrará uma div com um botão para cada opção do dropdown. Por enquanto tenho os divs (tenho que fazer mais) e o dropdown, mas não tenho o JS para mostrar e ocultar. Vai ficar só um a mostra.

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> TESTE </title>

    Qual a sua cidade?
    <select class="cat_dropdown" id="Cidade" name="Cidade">
    <option value="Florianopolis - sc">Florianópolis - SC</option>
    <option value="Joinville - sc">Joinville - SC</option>
    <option value="são josé - sc">São Joosé - SC</option>
    <option value="rio de janeiro - rj">Rio de Janeiro - RJ</option>
    <option value="porto alegre - rs">Porto Alegre - RS</option>
    </select>

<form action="https://pagseguro.uol.com.br/v2/pre-approvals/request.html" method="post">

<input type="hidden" name="code" value="6A2E84B72424217224353F91FCC1386A" />
<input type="image" src="http://beerkingstore.com.br/media/wysiwyg/bkclub/joinville-SC.png" name="submit" alt="Pague com PagSeguro - é rápido, grátis e seguro!" />
</form>

<form action="https://pagseguro.uol.com.br/v2/pre-approvals/request.html" method="post">

<input type="hidden" name="code" value="673830C750500BEDD4299F8B357559B9" />
<input type="image" src="http://beerkingstore.com.br/media/wysiwyg/bkclub/ASSINE-RJ-RJ.png" name="submit" alt="Pague com PagSeguro - é rápido, grátis e seguro!" />
</form>

<form target="pagseguro" action="https://pagseguro.uol.com.br/v2/pre-approvals/request.html" method="post">

<input type="hidden" name="code" value="1C52DCC32E2E6B1884B18F8740EB45F2" />
<input type="image" src="http://beerkingstore.com.br/media/wysiwyg/bkclub/assine-poa.png"     name="submit" alt="Pague com PagSeguro - é rápido, grátis e seguro!" />
</form>

Comment: Túlio, tem alguma framework como jQuery ou MooTools? ou prefere javascript puro?
Answer: Seria prático ter no seu HTML uma classe para todas as divs/cidades. Assim seria bem mais fácil selecionar todas essas divs

Para usar javascript simples pode usar assim
var select = document.querySelector('select#Cidade');
var cidades = document.querySelectorAll('.divcidade');

function esconder() {
    for (var i = 0; i < cidades.length; i++) {
        cidades[i].style.display = 'none';
    };
}

select.addEventListener('change', function () {
    esconder()
    var id = this.options[this.selectedIndex].value;
    document.getElementById(id).style.display = 'block';
});

esconder();

Exemplo
Esta solução funciona assim:

selecionar o select e guardar numa variável, e o mesmo com as divs das cidades
cria uma função que percorre todas as divs e as esconde
amarrar um event handler para correr codigo quando o select mudar
[quando o select mudar] esconder todas as divs e logo depois mostrar só aquela que tem o ID certo. Para isso usei o valor da option para selecionar um novo elemento por ID

Se não quiser mudar o HTML, pode usar assim também para gerar a array cidades:
var cidades = [];

for (var i = 0; i < select.options.length; i++) {
    var id = select.options[i].value;
    var estaCidade = document.getElementById(id);
    estaCidade && cidades.push(estaCidade)
}

Exemplo


Show nodes related to referenced node

Question: I have 3 content types: "Files", "Actions" and "Templates".

In each "Files" node there's a entity reference to an "Actions" node
In each "Templates" node there' a entity reference to an "Actions" node

How can I setup a view that shows a list of links to "Templates" nodes on a "Files" node page, based on the entity reference to an "Actions" node for this specific "Files" node?
Edit - I couldnt get Felix' answer to work, so here's a more detailed description of my case:
I have a node called "BAG001", this node has content type "Files.
I have a node called "Procedure A1", this node has content type "Actions"
I have a node called "Form A1", this node has content type "Templates"
In "BAG001" I make an entity reference to "Procedure A1" (field name is "field_action")
In "Form A1" I make an entity reference to "Procedure A1" (field name is "field_related_action")
On the "BAG001" page there's should be a views generated block, showing all templates related to "Procedure A1". In this case that would be "Form A1".
I tried setting up a view using the following settings:

1) Relationship -> Entity reference: field_action
2) Relationship -> (Content entity referenced from field_action) Entity Reference: Referencing Entity [with a relationship to (1)]
3) Contextual filter -> Content: NID [with a relationship to (2)]
Answer:
Create a view that shows a list of templates.
Add a relationship to the actions content type (Entity Reference: Referenced Entity via field_related_action).
Add a relationship to the files content type (Entity Reference: Referencing entity via field_related_action).
Create a contextual filter based on the current nodes nid. When you create the filter then When the filter value is NOT available select Provide default value and choose content ID from URL. Also this filter should be for the second join to the file node type.
Set that view to show in a block on each files page.
Comment: Nice, about the same time, the same format, the same number of steps (no longer true after your edit but oh well), totally different approach :D
Comment: @Mołot ah ha - but I added a step 5! :)
Comment: Hi Felix, thanks for your response. I've been fiddling around with contextual filters and relationships for hours, but can't get it to work :( I've tried the settings you described, but none of the template links show up.

in step 2, i take it you mean "Entity reference: actions" and in step 3 "Entity reference: referencing entity -> files".

Do i have to set the relationship in step 3 to the relationship added in step 2? And don't have to set a relationship for the contextuel filter?
Comment: The relationship in step 3 should indeed relate to actions. The contextual filter will use the nid of the file content type, so yes, it will be using a relationship.
Comment: Thanks for your reply felix, I've added the relationships, but still no output. I've edited my question with some more info, any other suggestions?
Comment: I've updated step 4 - does that make any difference?
Comment: I've just had a play recreating your setup and can confirm this method is working for me. My exported view looks [like this](http://pastebin.com/raw.php?i=c04wZ210).
Comment: Another tip is to add the nid that we are filtering on as a field to the view so you can actually make sure that it is populated correctly...
Comment: Thanks for all the help @FelixEve! I'm gonna have some dinner and report back to you when i'm done!
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14115/discussion-between-william-lekatompessy-and-felix-eve)
Answer:
Set reference field in Files content type to display Actions
Set up corresponding entity references between Actions and Templates
Create a display for Actions, that will display only corresponding entity references of Templates.
Use this display in 1.

Show nodes related to referenced node


User registration form validate and submit hooks not called

Question: I try to add custom validation or submit function to the user registration form, but nothing works.
Here is the code in /sites/all/themes/mytheme/template.php:
function mytheme_user_register_form_validate (&$form, &$form_state) {}
function mytheme_form_user_register_form_validate (&$form, &$form_state) {}
function mytheme_user_register_validate (&$form, &$form_state) {}
function mytheme_user_register_form_submit (&$form, &$form_state) {}
function mytheme_profile_user_form_validate (&$form, &$form_state) {}

I also put similar code to /sites/all/modules/custom/mymodule/mymodule.module:
function mymodule_user_register_form_validate (&$form, &$form_state) {}
function mymodule_form_user_register_form_validate (&$form, &$form_state) {}
function mymodule_user_register_validate (&$form, &$form_state) {}
function mymodule_user_register_form_submit (&$form, &$form_state) {}
function mymodule_profile_user_form_validate (&$form, &$form_state) {}

None of the above functions are called and I have ran out of ideas.
As a proof that something works on this form, here is something that does work:
function mytheme_form_user_register_form_alter(&$form, &$form_state, $form_id) {}

This gets called!! But I need to validate...
By the way, the debugger shows (among other) this when debugging the hook_form_alter:
$form['#validate'][0] = 'user_account_form_validate'
$form['#validate'][1] = 'user_validate_picture'
$form['#validate'][2] = 'user_register_validate'
$form['#validate'][3] = 'profile_user_form_validate'

Comment: First, your form functions shouldn't go into your theme, so you'd better use module hooks.

For your hooks to be taken into account, you have to clear the classes cache. Did you ?
Comment: It's not strange : theme is for presentation, module for business logic. You can use the simplest and more general hook for your form : hook_form_alter and then test for your form's name inside the hook. As for the custom function, petiar advice below is fine.
Comment: Yeah, I cleared all caches. It's a bit strange that validation must go to module and not theme, but anyway, module hooks don't work either.
Answer: Add this in your hook_form_alter:
$form['#validate'][] = 'your_validation_function';
This way you can define an additional validation functions. Make sure you report all validation errors using the form_set_error() function.
Comment: It is working! I was just wondering why the "normal" hooks don't get called. Nowhere in the documentation it is written that in order to use the hooks you have to add them manually to form validate array (and added function doesn't need to be strictly a hook, like in the example above)
Comment: It's the other way around : a validation function is just a standard function, not a hook. Hooks don't have to be added to be usable : you just have to use the correct namespace, which you probably didn't in your examples.
Comment: Considering all that was already said (use hook in a module and check form id for proper naming), my example contains one function that should be in the correct namespace: mymodule_user_register_form_validate (&$form, &$form_state) because the form id is "user_register_form". So at least this one should get called, according to [documentation](http://drupal.org/node/751826#validating)
Comment: @camcam Themes can just implement hooks called from `drupal_alter()`, which means those hooks whose name ends with "_alter()"; the other hooks cannot be implemented in themes.


Get the RootView controller from the dataViewController in UIPageViewController

Question: I have a rootViewController, which uses UIPageViewController to display some dataViewControllers, I'm wondering how can I get my rootViewController in dataViewController, sometimes I just need to refresh the UI of rootViewController, and I don't want to use Notification.
I use this in my dataViewController, however it only get me to the UIPageViewController.
- (UIViewController *)viewController
{
    for (UIView* next = [self.view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        NSLog(@"%@",[nextResponder class]);
        if ([nextResponder isKindOfClass:[UIPageViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

Answer: Your UIPageViewController can have weak reference to parent view controller (rootViewController) and pass that reference to other controllers which are nested in pageController.
You have to notice that all reference to parent controller(rootViewController) should be weak, in that way you will avoid strong reference cycles.


Programmatically create a new image style

Question: I'm creating my own module and I need to programmatically create an image style to use with a new media type.
I found the core/profile/standard/config/optional/image.style.max_1300x1300.yml file whose content is the following one.
name: max_1300x1300
label: 'Max 1300x1300'
effects:
  04caae9a-fa3e-4ea6-ae09-9c26aec7d308:
    id: image_scale
    data:
      width: 1300
      height: 1300
      upscale: false
    weight: 1
    uuid: 04caae9a-fa3e-4ea6-ae09-9c26aec7d308
langcode: en
dependencies:
  module:
    - responsive_image
  enforced:
    module:
      - responsive_image

I take I need to create a file in config/install, named image.style.<image_style_id>.yml, with those attributes.
What UUID values should I use?
Comment: It's in the admin under configuration.
Comment: @Kevin thanks but not my question, I don't want to use the UI
Comment: Writing out the yaml by hand is pointless. Make them in the UI and export them.
Answer: In answering this question, I assume that you have generated your configuration via UI, and then exported it, as Kevin mentioned in his comment. This is the best way to create the initial config for inclusion in your project.
Note that all examples are shown using procedural code for simplicity's sake; be sure to follow best practices and inject your services when building your project.

ImageStyle entity
Once that configuration file is installed, it becomes an ImageStyle configuration entity, and can be manipulated like any configuration entity.
// Get the storag ehandler for ImageStyle entities.
$image_style_storage = \Drupal::entityTypeManager()->getStorage("image_style");
// Get an instance of our ImageStyle entity.
$my_image_style = $image_style_storage->load("my_image_style");

The effects that are specified in the ImageStyle definition are plugins managed by the plugin.manager.image.effect plugin manager service.
As luck would have it, the ImageStyle entity offers the addImageEffect() public method, which accepts an array of effects info. This method actually takes care of generating and assigning the UUID, which is then returned to you.
public function addImageEffect(array $configuration) {
    $configuration['uuid'] = $this->uuidGenerator()->generate();
    $this->getEffects()->addInstanceId($configuration['uuid'], $configuration);
    return $configuration['uuid'];
  }

So, using your image.style.max_1300x1300 example, assigning the image effect would look like:
$effect_uuid = $my_image_style->addImageEffect([
  'id' => 'image_scale',
  'data' => [
      'width' => '1300',
      'height' => '1300',
      'upscale' => FALSE,
   ],
   'weight' => 1,
]);

You can find all of the image effects registered on your site by executing:
\Drupal::service('plugin.manager.image.effect')->getDefinitions();


Ordered logit with independent variable only taking negative values

Question: I have a continuous independent (explanatory) variable that takes on negative values only. How do I interpret a negative coefficient on this variable?
The dependent variable is ordered as 1,2,3.
Is it the usual interpretation that the log odds are lower as we move from 1 to 2 and then 2 to 3?
Thanks
Comment: Hi, there seems to be some confusion in whether your dependent or independent variable is always negative. Can you correct your question so that this will be clear, please?
Comment: Done. Sorry about that
Answer: Yes, the ordered logit is linear in the log-odds, so the fact that values of your explanatory variable are negative has no impact on the slope and its interpretation. If they are all negative I would use examples like going from -2 to -1 or -3 to -2, but otherwise there is no difference.
Comment: Thanks. So going from -2 to -1 reduces the log odds of being in category 2 vs. category 1 and so on? or is it if one goes from -1 to -2, the log odds of being in category 2 are lower than that of being in category 1?
Comment: If your explanatory variable increases by one unit (e.g. going from -2 to -1, as $-2 + 1 = -1$) and the coefficient is negative, then that will decrease the log odds of entering category 2 of your explained variable compared to category 1.
Comment: If your explanatory variable decreases by one unit (e.g. going from -1 to -2) and the coefficient is negative then the log odds of entering category 2 of your explained variable compared to category 1 will increase.


Finally installed MySQL for Rails in Windows 64 bit, and now

Question: Environment:
Windows 7 64bit (Home Premium)

Ruby 1.9.2 p290 (2011-07-09) [i386-mingw32]

Rails 3.0.10

MySQL 5.5

Ruby, despite my having successfully installed the mysql2 rubygem thinks that the gem is missing when I invoke a rails command that requires it.
After having spent the evening getting the mysql rubygem installed on Windows 64 bit, I decided to (finally) get cracking on linking mysql to a local rails server. This is how I was trying to do it...
(Fairly) Exact transcript from cmd.exe
C:\rails\cookbook>gem install mysql --platform=ruby -- --with-mysql-include=c:\mysql\include --with-mysql-lib=c:\mysql\lib
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
Successfully installed mysql-2.8.1
1 gem installed
Installing ri documentation for mysql-2.8.1...
Installing RDoc documentation for mysql-2.8.1...
(I thought this was successful mysql install, should I test it somehow?)

C:\>gem install mysql2 --platform=ruby -- --with-mysql-include=c:\mysql\include --with-mysql-lib=c:\mysql\lib
Fetching: mysql2-0.3.7.gem (100%)
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
Successfully installed mysql2-0.3.7
1 gem installed
Installing ri documentation for mysql2-0.3.7...
Enclosing class/module 'mMysql2' for class Client not known
Installing RDoc documentation for mysql2-0.3.7...
Enclosing class/module 'mMysql2' for class Client not known
(Same as above - I thought this was successful mysql install)

C:\rails>rails new cookbook -d mysql
(successfully creates directories for project in c:\rails\cookbook)

C:\rails\cookbook>rails server
?[31mCould not find gem 'mysql2 (~> 0.2.11)' in any of the gem sources listed in your Gemfile.?[0m
?[33mRun `bundle install` to install missing gems.?[0m

Notes:
I noticed it wants rubygem mysql2-0.2.11, I have 0.3.7. I tried installing 0.2.11 specifically by the method I used to install the two gems above. No dice, it couldn't find a gem by the name mysql2-0.2.11 in 'any repository'
I'm stumped, any thoughts fellas (and gals)?
Comment: Windows isn't the best platform for ruby web development. I suggest making a Linux VM with VirtualBox and Vagrant (http://vagrantup.com/) unless you have a specific need to run on Windows. If your actual deployment environment is Linux it certainly is in your best interest to develop in a Linux VM so your production and dev envs are as close as possible. I don't think you'll run into any of these problems with a Linux box as that's what most developers use and you'll be able to get more access to help.
Comment: @Cixate or at the minimum something like sqlite3 which has much more mature integration with Windows + RoR
Answer: I believe your MySQL installation is a 64bits (like Windows), correct?
Ruby is 32bits, so you cannot link 32bits against 64bits.
I've posted a article covering the installation steps on my blog:
http://blog.mmediasys.com/2011/07/07/installing-mysql-on-windows-7-x64-and-using-ruby-with-it/
These steps use MySQL Connector/C to workaround the 32bits versus 64bits issues.
Both mysql or mysql2 gem should work with this.
Comment: Happy to hear! don't forget to mark the question as resolved so other finds it!
Answer: Have you included mysql2 in your Gemfile and subsequently executed bundle install ?
Answer: @@ my sql installation (on 64 bit architecture)
download connector (download zip file and extract it to c drive)
http://dev.mysql.com/downloads/connector/c/
download mysql
http://dev.mysql.com/downloads/installer/5.6.html
command to install mysql with connector
C:\Sites\rails_project\resume>gem install mysql --platform=ruby -- --with-mysql-
dir=C:/mysql-connector-c-6.1.0-win32

After this copy libmysql.dll from connector folder and paste it to ruby>bin folder


Média entre vetores dentro de funções (python)

Question: Boa tarde pessoal, tenho o seguinte código:
def Ler_vetor():
VET= []*10
for i in range(0,10):
    VET.append(int(input('Digite um número: ')))
return VET

def Escreva_vetor(VET):
print('Dentro do vetor (permutado) tem:',VET)

def Somar_vetor(VET):
pares = []
for i in range (0,10):
    if VET[i] % 2 == 0:
        pares.append(VET[i])
soma = sum(pares)
print('A soma dos pares é: ',soma)
return pares

def Contar_vetor(VET):
contador = 0
for i in range (0,10):
    if VET[i] % 2 == 0:
        contador += 1
print('Possui dentro do vetor: {} pares'.format(contador))
return contador

def Trocar_vetor(VET):
for i in range(0,10,2):
    aux = VET[i]
    VET[i] = VET[i+1]
    VET[i+1] = aux

print('----- Vetor A : -----')
vetA = Ler_vetor()
Somar_vetor(vetA)
Contar_vetor(vetA)
Trocar_vetor(vetA)
Escreva_vetor(vetA)

Basicamente ele lê um vetor de 10 posições, soma todos os pares, conta quantos pares tem, troca os impares de posição jogando para frente e escreve.
essa parte para o que preciso está OK.
Agora precisaria fazer a média aritmética dos números pares dentro do vetor e não consigo de maneira nenhuma, sendo que essa média não pode ser através de função e sim no programa principal, abaixo do Escreva_vetor(vetA).
Alguém poderia me ajudar?
Aqui um exemplo da saída:
----- Vetor A : -----
Digite um número: 1
Digite um número: 2
Digite um número: 3
Digite um número: 4
Digite um número: 5
Digite um número: 6
Digite um número: 7
Digite um número: 8
Digite um número: 9
Digite um número: 10
A soma dos pares é:  30
Possui dentro do vetor: 5 pares
Dentro do vetor (permutado) tem: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]

Answer: Segue a solução conforme o enunciado:
def Ler():
    entrada = input('Entre com o vetor: ')
    return [ int(n) for n in entrada.split(",") ]

def Somar(v):
    return sum(v)

def Contar(v):
    return len(v)

def Pares(v):
    return [ n for n in v if not n % 2 ]

def Somar_Pares(v):
    return Somar(Pares(v))

def Contar_Pares(v):
    return Contar(Pares(v))

def Trocar(v):
    vaux = v[:]
    for i in range( 0, len(vaux) - 1, 2 ):
        vaux[i], vaux[i + 1] = vaux[ i + 1 ], vaux[i]
    return vaux

# 1 - Leia dois vetores de numeros inteiros de 10 posicoes
v1 = Ler()
v2 = Ler()

# 2 - Imprima os dois vetores lidos
print("Vetor A: {}".format(v1))
print("Vetor B: {}".format(v2))

# 3 -  Calcule a soma dos numeros pares contidos em cada vetor.
print("Soma dos Numeros Pares do Vetor A: {}".format(Somar_Pares(v1)))
print("Soma dos Numeros Pares do Vetor B: {}".format(Somar_Pares(v2)))

# 4 - Conte quantos valores pares existem em cada vetor
print("Qtd. de Numeros Pares no Vetor A: {}".format(Contar_Pares(v1)))
print("Qtd. de Numeros Pares no Vetor B: {}".format(Contar_Pares(v2)))

# 5 - Para cada vetor lido no item a troque os elementos de ordem impar
#     com os de ordem par imediatamente seguinte para cada vetor
vtr1 = Trocar(v1)
vtr2 = Trocar(v2)

# 6 - Imprima os dois vetores apos as trocas.
print("Vetor A Trocado: {}".format(vtr1))
print("Vetor B Trocado: {}".format(vtr2))

# 7 - No programa principal calcule a media aritmetica dos numeros pares
#     contidos nos vetores
pares1 = [ n for n in v1 if not n % 2 ]
pares2 = [ n for n in v2 if not n % 2 ]

media1 = sum(pares1) / float(len(pares1))
media2 = sum(pares2) / float(len(pares2))

print("Media Vetor A: {}".format(media1))
print("Media Vetor B: {}".format(media2))

# Fim #

Saída:
Entre com o vetor: 1,2,3,4,5,6,7,8,9,10
Entre com o vetor: 1,3,5,7,9,2,4,6,8,8
Vetor A: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Vetor B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 8]
Soma dos Numeros Pares do Vetor A: 30
Soma dos Numeros Pares do Vetor B: 28
Qtd. de Numeros Pares no Vetor A: 5
Qtd. de Numeros Pares no Vetor B: 5
Vetor A Trocado: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
Vetor B Trocado: [3, 1, 7, 5, 2, 9, 6, 4, 8, 8]
Media Vetor A: 6.0
Media Vetor B: 5.6

Comment: Opa amigo obrigado pela resposta, mas sou "obrigado" a fazer o resto com funções:
Leia dois vetores de números inteiros de 10 posições;
Imprima os dois vetores lidos;
Calcule a soma dos números pares contidos em cada vetor.
Conte quantos valores pares existem em cada vetor
Para cada vetor lido no item a troque os elementos de ordem ímpar com os de ordem par imediatamente seguinte para cada vetor
Imprima os dois vetores após as trocas.
Os itens anteriores devem ser desenvolvidos por meio de funções.No
programa principal calcule a média aritmética dos números pares contidos nos
vetores
Comment: @GustavoSantos: Feito!
Comment: Opa muito obrigado, entretanto me retornou esse erro:

`Traceback (most recent call last):
Vetor A: [5]
Vetor B: [8]
  File "C:/Users/Dovah/PycharmProjects/trabalhoPROG/Trabalho2.py", line 56, in
Soma dos Numeros Pares do Vetor A: 0
    media1 = sum(pares1) / float(len(pares1))
Soma dos Numeros Pares do Vetor B: 8
ZeroDivisionError: float division by zero
Qtd. de Numeros Pares no Vetor A: 0
Qtd. de Numeros Pares no Vetor B: 1
Vetor A Trocado: [5]
Vetor B Trocado: [8]`
Comment: Repare que a entrada de dados é feita no formato: `n1, n2, n3, ...`
Comment: Falta de atenção minha, muito obrigado irei estudar o código e tentar refazer!!


Does NSMutableAttributedString automatically concatenate identical adjacent attributes?

Question: We have a simple markup parser in our iOS app that takes text with HTML-like tags and converts it into an NSAttributedString by iterating over each character in a simple NSString and producing an NSMutableAttributedString.
In a worst case scenario where we added a new set of attributes to every single character as we iterated through a string, would the NSMutableAttributedString be intelligent enough to join the identical adjacent attribute ranges together and optimize? Or would it be horribly inefficient and slow to render in Core Text?
I'm not suggesting this is a good algorithm in general! I'm just looking at a worst case scenario, and wondering whether the NSMutableAttributedString has any built in intelligent behaviour?
Comment: Have you figured this out yet? I have some similar code running in my app and I could feed it some input to trigger this behavior and see what output I get.
Comment: Nope, never found out. Ignored the issue because it wasn't causing any problems, but I'd still love to know the answer!
Answer: I just tried something like this (a simplified version of my real code):
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Testfoobarhey"];
UIFont *font = [UIFont fontWithName:@"Georgia-Bold" size:12.0];
[text addAttribute:NSFontAttributeName value:font range:NSMakeRange(4, 3)];
[text addAttribute:NSFontAttributeName value:font range:NSMakeRange(7, 3)];

In other words, I added two bold attributes right next to each other. Then I viewed the result:
NSLog(@"%@", text);

And the output showed three chunks of text: "Test" in normal font, "foobar" in bold, and "hey" in normal font.
So to answer your question, yes, it looks like the two adjacent formatting ranges were joined automatically in the NSMutableAttributedString.
P.S. On a related note, I've noticed that if I apply an attribute with a range that extends across a line break, the resulting NSAttributedString will have one attribute before the line break and another after, and the line break itself won't have any attributes. So if you're ever parsing one character at a time, you might need to compensate for that.
Comment: Nice. I also just tried a simple test of appending another `NSAttributedString` and it correctly concatenated the attributes from that too.


How to put links into description text?

Question: In my field's description, I want to link to more documentation. If I do it like this:
$form['field_name'] = array (
  '#description' => t('Here are some words about') . ' ' . t('stuff') . ' ' . t('and things and whatnot'),
);

It works. It looks like this:

Here are some words about stuff and things and
  whatnot.

If I do it the proper way, like this:
$form['field_name'] = array (
  '#description' => t('Here are some words about @stuff and things and whatnot', array('@stuff' => l('stuff', 'blah')),
);

Then the HTML is generated and then output into my description as raw text, like so:

Here are some words about stuff and things and
  whatnot.

Why is the "correct" way not working?
Answer: Firstly, here are some of the ways NOT to pass links to the t() function:
// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => ''. t('the Drupal Handbooks') .''));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at the Drupal Handbooks.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

And these are the accepted ways to pass that type of arg:
// Do this instead.
$external_link = t('Look at Drupal documentation at the Drupal Handbooks.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to the Administer screen in the main menu.', array('@administer-page' => url('admin')));

This all comes from Dynamic or static links and HTML in translatable strings, which contains justifications for that reasoning.
Comment: Whoops, yes you're right.
Comment: The first one is what I did already.
Comment: @beth Do you mean the one called `$BAD_EXTERNAL_LINK`? That (and the other two in that block) are what ***not*** to do. The second code block contains the correct code to use. Neither of those are the same as what you tried

How to put links into description text?


facebook sharer og:url content not displayed after share

Question: I have set the meta tags as shown in the example
Everything works fine, except the og:url tag. Before i hit the share button, it's displaying the correct url as set in the tag. But after I hit the share button, the shared message display the domain name of the site instead. So for example if I set the og:url as www.helloworld.com/hellouniverse, the shared message (this can be seen after i hit share) will instead display www.helloworld.com.
Does anyone probably have any idea how to fix this ?
Thanks
Comment: First check the Facebook debugger:
https://developers.facebook.com/tools/debug

If that looks good than please post a URL to your site or the HTML source for your tags.
Answer: As far as I know, this is the default behavior of facebook, they take the domain name from the og:url parameter and display it.
I've tried several approaches to deal with it, but eventually came up with nothing.
Because it is their internal script, there isn't much you can do about it.


Using "Profile" Data

Question: I have used "Profiles 2" module, and created a form where users can input their profile data.
I have also defined a content type, say "Blog" for example, which has a title and a body. I have used "Views" module to generate the output.
The question is, I would like to display a line like :
'Posted By : '
Is there a way I can extract the data from Profiles?
Answer: Yes, you use relationships under advanced to first expose the Content:Author. Then you use relationships again which will now show the User:Profile relation. Now you will have access to all the user details :)
It should look like this when you are done:

Comment: I think this would show the username? I am trying to get the "First Name" field, which is an extension of the core profile i believe

Using "Profile" Data


How to cache viewholder view references in android recyclerView

Question: From the android docs

This new ViewHolder should be constructed with a new View that can represent the items of the given type. You can either create a new View manually or inflate it from an XML layout file.

but then it continues to say:
The new ViewHolder will be used to display items of the adapter using onBindViewHolder(ViewHolder, int, List). Since it will be re-used to display different items in the data set, it is a good idea to cache references to sub views of the View to avoid unnecessary findViewById(int) calls.
Can i have an example what is mean tby caching referenences to sub views of the view instead of calling findViewbyId.  I mean in the viewholders constructor i am already calling findviewbyId. something like this:
public class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView review;
    public ImageView iv;

    public MyViewHolder(View view) {
        super(view);
        review = (TextView) view.findViewById(R.id.gridview_text);
        iv = (ImageView) view.findViewById(R.id.gridview_image);

    }
}

is this not correct ? how can these be cached ?
Comment: everytime a viewHolder is instantiated findViewById will be called per my example. Isn't MyViewHolder's constructor called for every cell being created in the list ? How is it then called caching if its called for every list item.
Comment: It's cached because a single View "template" is used for all items in the data set that will fill your RecyclerView, so they only need to be initiated once. What you have there is correct - be sure that any `onClick` listeners are either in your holder's constructor or handled via interface, NEVER in the `onBindViewHolder()` method.
Answer: What you posted is exactly what they mean by caching the views in the viewholder. This prevents having to use findViewById() every time you need to bind data to it.
Comment: i am a little confused.  for every single cell in the recyclerView a viewHolder object needs to created. So findviewById is called many times initially.  But when a cell is recycled i assume a new viewHolder object will not be instantiated it will just reuse from some pool.  is this correct ?
Comment: @j2emanue yes, that's correct. Hence the name "**Recycler**View". That's why it's recommended you use `findViewById()` initially and keep references to those views (like your code does) so you don't have to do that again when you bind data to the viewholder.


When are maps between topological manifolds automatically surjective?

Question: Take an injective (continuous) map $T:\mathbb{S}_1\to\mathbb{S}_1$. It's an obvious fact (though I can only prove it with nontrivial facts about homotopy) that $T$ is automatically surjective.
I have two questions:

Is this the case for all 'endomorphisms' of spheres? (I think so, but have not proven it)
Does there exist a compact manifold without boundary which embeds nontrivially into itself?

I suspect the answer to the second question is 'no', but I have little evidence for the conjecture.
Comment: The second question follows (negatively) from the theorem of invariance of domain (http://en.m.wikipedia.org/wiki/Invariance_of_domain#section_3), which says that that such a map is open (and since your manifold is compact, the image is closed and open, and solves the problem for connected manifolds, then you use that there are finitely many connected components)
Comment: $\newcommand{\ra}{\rightarrow}$If $f: S^n \ra S^n$ misses a point then by stereographic projection it induces a map $f: S^n \ra R^n$ so if there were an injective non-surjective map from $S^n$ to $S^n$, then $S^n$ would embed in $R^n$. For your second question you might try creating a descending chain by repeated applications of your embedding or something along those lines.
Comment: The second question is interesting because both "compact" and "without boundary" are essential, and it's hard to see how they interact.
Comment: Thinking about the degree of such a map should be profitable. If a map misses a point, it must have degree zero. I'm not sure if this is enough to rule out an embedding, though.
Comment: Thanks for the reference - very cool :)
Answer: This is a CW answer to record that the question is answered in the comments. If someone upvotes this, the question will be removed from the unanswered list (and I will not receive reputation, because it is CW).


Calculus for Statistics

Question: If one were to learn calculus solely for the purpose of learning statistics, what should he focus on? If this is a ridiculous question and the honest answer is "All of it," that is of course an acceptable answer. But if not, what aspects of calculus are particularly salient for learning statistics? Can certain parts be skipped over or should certain parts be emphasized? Welcoming input from anyone conversant in both advanced calculus and advanced statistics. Thanks in advance!
Comment: To do what kind of statistics? If all you want to do is calculate some means and standard deviations in Excel, maybe make some plots, then you don't need *any* calculus. If you want to be a mathematical statistician, you'll need more calculus.
Comment: I mean to the degree that I could work cover to cover through a statistics textbook who's preface reads something along the lines of "the reader is assumed to have a working knowledge of calculus."
Comment: Taylor series was something I wished I had paid more attention to
Comment: If you want to cover advanced probability, you need to go beyond calculus to analysis and measure theory.
Comment: Start by getting a good grasp of derivation and integration. Maybe not becoming great at solving integrals, but rather trying to understand them conceptually and what they means in the context of statistics.
Comment: It depends what kind of statistics you are aiming for. If you want to focus on Time Series then Infinite Series would be most important (+ some Linear Algebra + some Real Analysis would make you king). For most other things you need pretty much everything in Single Variable Calculus, and just a thing or 2 from Multivariate Calculus. Multivariate Calculus as taught these days is decidedly not customized for Statistics. If you focus on Probability, then Real Analysis will be necessary.
Comment: Related: [Book recommendations needed - building foundational knowledge for ISL - Introduction to Statistical Learning (by Gareth James)](https://stats.stackexchange.com/q/486182/1352), which I found by looking through [threads tagged both "calculus" and "references"](https://stats.stackexchange.com/questions/tagged/calculus%2breferences).
Answer: Learn how to differentiate and integrate, and what each of these concepts mean when applied to multi variate functions. I mean Riemann integrals. This alone will get you a long way in statistics. It's like knowing how to ride a bus and subway in the city. You can get anywhere within the city limits.
I'm assuming you don't include the probability theory in your ask, because that is a whole different level of mathematics. This would be like having a 4x4 car, so you get to venture outside your town on your own.
Answer: In addition to the very good answer by Aksakal, a few more suggestions:

Yes, differentiation and integration, especially stuff like the chain rule. Pay particular attention to Taylor series, as jros recommends. A low-order approximation is often helpful.

A rudimentary grasp of linear algebra, especially matrix operations: matrix multiplication, matrix inversion and why doing it directly is usually not a good idea. Yes, this is not calculus per se, but differentiation is really nothing else than linearization, i.e., taking a nonlinear function and approximating it locally by a linear mapping - which is exactly matrix multiplication. Thus, most textbooks on multivariate calculus presuppose this knowledge, or include a quick introduction.
Useful slightly more advanced linear algebra would be eigenvalues/eigenvectors and common matrix decompositions, for PCA and conditioning analysis.

Mathematical induction comes in handy once in a while when you deal with discrete probability. Again, not calculus as such, but a frequent prerequisite and helpful.

Perhaps some understanding of dealing with infinite sums, again for discrete probabilities. Happily, our probabilities are nonnegative, so we can usually do dangerous stuff like interchanging summation and differentiation/integration without worrying about absolute convergence. As ColorStatistics notes, this is especially helpful for time series analysis of the ARIMA variety (which in turn I do not find very helpful for practical use, but I don't know whether you are interested in this), and of course Taylor series per above are a special case of power series.

Per multiple comments: if you want to go deeper into probability theory, then you want to understand measure theory and more advanced integration, e.g., the Lebesgue integral. You will typically find material like this in books on Real Analysis. However, if the stats textbook you want to understand only presupposes "a working knowledge of calculus", then measure theory is definitely not needed. (Fun, though.)

Calculus for Statistics


Installing Lync 2013 sdk client side on visual studio 2015

Question: I am trying to install the Lync 2013 SDK on Visual studio 2015, but I get an error saying "MSVS2010 SP1 or higher not found. Go here to download and install"
I've looked up the issue on the web, and the closest thing to a solution is installing a cumulative update, but that was for VS2013, nor can I find any Place to actually download the file.
What do I have to do to complete the Lync 2013 SDK setup?
Comment: This question seems more suited for [SuperUser](http://superuser.com/questions).
Answer: To install the SDK, you can fake that you have an earlier version of Visual Studio. At least, that seemed to work for me.
What I did was export the registry entries at HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\Setup\vs, searched and replaced VisualStudio\14.0 with VisualStudio\12.0 and imported those registry entries again.
That allowed me to install the SDK and I subsequently removed those imported entries again.
Please make sure (using regedit) that you are not overwriting any existing entries of course.
Comment: Also see this [link](http://stackoverflow.com/a/35934759/552448) Use Universal Extractor or a similar tool to unpack the SDK kit, then use the appropriate MSI.
Comment: Works nicely with VS2015


Do such sequences exist?

Question: I wish to know if there are real sequences $(a_k)$, $(b_k)$ (and if there are, how to construct such sequences) such that:
$b_k<0$ for each $k \in \mathbb{N}$ with  $\lim\limits_{k \rightarrow \infty} b_k=-\infty,$
$$\sum_{k=1}^\infty |a_k| |b_k|^n< \infty, \space\forall n\in\mathbb{N}\cup\{0\}$$
$$\sum_{k=1}^\infty a_k b_k^n=1, \space \forall n\in\mathbb{N}\cup\{0\}$$
Comment: what about $b_k = -k$ with $a_1 = -1$ and $a_k =0$ for $k \ge 2$ ?
Comment: @mercio: Then for every even positive $n$, the sum is $-1$ instead of $1$.
Answer: For any unbounded sequence $(b_k)$ and any sequence $(\lambda_n)$, you can find a sequence $(a_k)$ such that for any $n$, $\sum_{k=1}^\infty a_k b_k^n$ converges absolutely to $\lambda_n$ :
Suppose you have constructed $a_k$ up to some index $k_0$, such that for all $m < n$, $\sum_{k=1}^{k_0} a_k b_k^m = \lambda_m$. The goal now is to extend this up to some index $k_1$ such that for all $m \le n$, $\sum_{k=1}^{k_1} a_k b_k^m = \lambda_m$, with "arbitrarily small coefficients".
This means we have to add $y = \lambda_n - \sum_{k=1}^{k_0} a_k b_k^n$ to the partial sum of the $n$th series, and $0$ to the first $n-1$ series.
In order to do that, look at the next $n-1$ distincts values of $b_k$ (for $k > k_0$), say they are $c_1,c_2, \ldots c_{n-1}$, look at the Vandermonde matrix
$$ M(X) = \begin{pmatrix} c_1^1 & \ldots & c_{n-1}^1 & X^1 \\ \vdots & & \vdots & \vdots \\  c_1^n & \ldots & c_{n-1}^n & X^n \end{pmatrix}$$
and solve for the vector $A(X)$ in the equation $M(X) A(X) = (0,0,\ldots,0,y)$.
We get that $A(X)$ has to be $y$ times the $n$th column of $M(X)^{-1}$.
Thus $A(X)$ is $y/det(M(X))$ times the transpose of the $n$th row of the comatrix of $M(X)$.
If you look carefully at this row, each entry there is a polynomial in $X$ of degree $n-1$, except the last one which is a constant. Furthermore, the determinant of $M(X)$ is of degree $n$, so the entries of the vector $A(X)$ are rational fractions of degree $-1$ and $-n$.
In particular, for $X$ large enough, $\sum_{1 \le i,j \le n-1} |A_i(X)c_i^j| < 2^{-n}$
Thus, if you pick $k_1$ such that $b_{k_1}$ is large enough, you will get from $A(b_{k_1})$ the coefficients to put in front of $c_1^n, c_2^n, \ldots, c_{n-1}^n, b_{k_1}^n$ such that all the partial sums are what we want, and the absolute contribution to what we added to each partial sum is less than $2^{-n-1}$.
Now, repeat this procedure for all $n$, and you get a suitable sequence $(a_k)$.
Answer: Let $(b_n)$ be any negative sequence diverging to $-\infty$, and suppose such a sequence $(a_k)$ exists.
Let $K \in \mathbb{N}$ be such that $b_k < -2$ for all $k \ge K$. Then
$$\sum_{k=1}^{\infty} \left| a_k \right| \left| b_k \right|^n \ge \sum_{k=K}^{\infty} \left| a_k \right| \cdot 2^n = 2^n \sum_{k=K}^{\infty} \left| a_k \right|$$
So for all $k \ge K$ we require $a_k = 0$. So then
$$\sum_{k=1}^{\infty}a_kb_k^n = \sum_{k=1}^{K-1}a_kb_k^n = 1$$
And so for all $n \in \mathbb{N}$ we have
$$\sum_{k=1}^{K-1} a_k(b_k^n - b_k^{n-1}) = 0$$
So in $\mathbb{R}^{K-1}$ the vector $(a_k)_1^{K-1}$ is linearly independent from the vectors $(b_k^{n-1}(b_k - 1))_1^{K-1}$ for each $n \in \mathbb{N}$. Since $b_k \ne 1$ and $(a_k) \ne 0$, this must mean that the $(b_k^{n-1}(b_k-1))$ all lie in the $(K-2)$-hyperplane orthogonal to $(a_k)$. But unless each $b_k=-1$, these span a $(K-1)$-dimensional subspace (i.e. the whole of $\mathbb{R}^{K-1}$), so we must have $b_k=-1$ for each $k$. Therefore
$$\sum_{k=1}^{K-1} (-1)^na_k = 1$$
for all $n \in \mathbb{N}$. This is a contradiction (multiply through by $-1$).
Comment: I don't think the bit where you use linear independence works: the $(b_k^{n-1}(b_k-1))_1^{K-1}$ are all orthogonal to $(a_k)_1^{K-1}$ but we don't know that they're linearly independent with eachother?
Comment: I didn't know you were on MSE @Tom! And yes, good point, I'll see if I can find a way round it. I might not be able to.
Comment: I think I've thought of how to do it
Comment: @TomHutchcroft: I think I fixed it by referring to the hyperplane orthogonal to $(a_k)$ rather than the linear independence of the vectors. Give me a moment to go over the details again in my head.
Comment: I've got a proof that doesn't use any linear algebraic arguments, I guess I'll post it
Comment: Sure thing, it's no doubt much simpler!
Comment: your argument in order to show that $a_k = 0$ for $k \ge K$ supposes that there is a bound on $\sum |a_k b_k^n|$ that doesn't depend on $n$. The question only says that there is a bound for each $n$, if I read it correctly.
Answer: Let $(b_n)$ be a negative sequence diverging to $-\infty$, and suppose such a sequence $(a_k)$ exists.
Let $K \in \mathbb{N}$ be such that $(b_k) < -2$ for all $k \geq K$. Then $\sum_{1}^{\infty}\mid a_k\mid \mid b_k \mid ^n \geq \sum_K^\infty\mid a_k\mid \mid b_k \mid ^n \geq (2)^n\sum_K^\infty\mid a_k\mid $
So for all $k \geq K$ we have $a_k=0$. (So far copying Clive!)
Now write $\sum_{1}^{\infty}\mid a_k\mid \mid b_k \mid ^n = \sum_{1}^{K-1}\mid a_k\mid \mid b_k \mid ^n= \sum_{b_k>-1}^{k < K}\mid a_k\mid \mid b_k \mid ^n + \sum_{b_k=-1}^{k < K}\mid a_k\mid \mid b_k \mid ^n +\sum_{b_k<-1}^{k < K}\mid a_k\mid \mid b_k \mid ^n$
Similarly to before, we have $\sum_{1}^{\infty}\mid a_k\mid \mid b_k \mid ^n \geq \sum_{b_k<-1}^{k < K}\mid a_k\mid \mid b_k \mid ^n \geq \min_{k<K, b_k<-1}(\mid b_k \mid) ^n \sum_{b_k<-1}^{k < K}\mid a_k\mid $  so we must have that $a_k = 0$ whenever $b_k <-1$.
Now we have $\sum_{1}^{\infty} a_k  b_k  ^n = \sum_{b_k>-1}^{k < K} a_k  b_k  ^n + (-1)^n\sum_{b_k=-1}^{k < K} a_k =1$ and taking the limit as $n$ tends to $\infty$ we have that $(-1)^n\sum_{b_k=-1}^{k < K} a_k$ tends to 1, a contradiction.
Comment: your argument in order to show that $a_k = 0$ for $k \ge K$ supposes that there is a bound on $\sum |a_k b_k^n|$ that doesn't depend on $n$. The question only says that there is a bound for each $n$, if I read it correctly.
Comment: Oops! You're right.

Do such sequences exist?


Taylor Expansion of complex function $ \frac{1}{1 - z - z^2} $

Question: Knowing that

$$c_{n+2}=c_{n+1}+c_n, \quad n \geq 0,$$

the problem is to prove that we have

$$ \frac{1}{1 - z - z^2}=\sum^{+\infty}_{n=0} c_nz^n.$$

I have tried to transform the function into the form:
$$ A(\frac{1}{z-b_1}+\frac{1}{b_2-z})$$
Then expand $\frac{1}{z-b_1} \text{and} \frac{1}{b_2-z}$
However, the result seems having nothing to do with $c_{n+2}=c_{n+1}+c_n$
Am I wrong? How should I prove this in a elegant way?
Answer: Hint:
$$
(1-z-z^2)\sum_{n\ge 0}c_nz^n = 1
$$
What is the coefficient of $z^n$ on the each side?
Answer: You may start from
$$c_{n+2}=c_{n+1}+c_n, \quad n\geq0. \tag1$$
Multiply $(1)$ by $z^{n+2}$ and sum over $n\geq 0$ then you obtain
$$
\begin{align}
\sum^{+\infty}_{n=0} c_{n+2}z^{n+2}&=\sum^{+\infty}_{n=0} c_{n+1}z^{n+2}+\sum^{+\infty}_{n=0} c_{n}z^{n+2}\\
\sum^{+\infty}_{n=0} c_{n+2}z^{n+2}&=z\sum^{+\infty}_{n=0} c_{n+1}z^{n+1}+z^2\sum^{+\infty}_{n=0} c_{n}z^{n}\\
\sum^{+\infty}_{n=0} c_{n+2}z^{n+2}&=z\sum^{+\infty}_{n=1} c_{n}z^{n}+z^2\sum^{+\infty}_{n=0} c_{n}z^{n}\\
\sum^{+\infty}_{n=0} c_{n}z^{n}-c_0-c_1z&=z\sum^{+\infty}_{n=0} c_{n}z^{n}-c_{0}z+z^2\sum^{+\infty}_{n=0} c_{n}z^{n}\\
\end{align}
$$ and you readily obtain
$$ \frac{1}{1 - z - z^2}=\sum^{+\infty}_{n=0} c_nz^n$$ taking into account that $c_0=1$ and $c_1=1$.
Answer: use this
$$\frac{8 x^2}{\sqrt{5} \left(\sqrt{5}+1\right)^2 \left(2 x+\sqrt{5}+1\right)}+\frac{8 x^2}{\sqrt{5} \left(\sqrt{5}-1\right)^2 \left(-2 x+\sqrt{5}-1\right)}+x+1$$
Comment: ok not problem it is a expansion laurent series with two poles
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/826811)


copying a list into part of a numpy array

Question: I have a list that varies in size and I would like to copy it over a numpy array. I already have a way to do but I would like to see if there is a more elegant way.
Let's say I have the following:
import numpy as np
data = np.full((10,), np.nan)

# I want to copy my list into data starting at index 2
def apply_list(my_list):
    data[2:2+len(mylist)] = mylist

# Example
tmp = [1, 2, 3, 4]        # can vary from 2 to 8 elements
apply_list(tmp)

After this, I expect data to look like this:
[nan, nan, 1, 2, 3, 4, nan, nan, nan, nan]

Please keep in mind that len(mylist) can range from 2 to 8.
I am marking unused places with NaN and data has been preallocated and should always be size=10, regardless of the size of my_list. For that reason, simply appending will not work.
I particularly don't like much doing 2:2+len(mylist). Is there a nicer/cleaner way of doing this?
Comment: That's the simplest way to do the job.
Comment: You case matches the 2nd example in this pararagraph: https://docs.scipy.org/doc/numpy/user/basics.indexing.html#assigning-values-to-indexed-arrays, `x[2:7] = np.arange(5)`.  Assignment to a list works the same way - except that the RHS slot does not have match in size.  Array size is fixed, list size is not.
Comment: Is there some way of combining this with some iterator/generator? (obviously without having to iterate in plain python). I know about np.fromiter but not sure how to connect that to the assignment
Comment: Are you looking for speed or pretty code?
Comment: well.. both :). I am learning more about numpy and I came up with this problem. If I can improve style, it would be great. But clearly I dont want to have a performance hit.
Answer: I'm not aware of any numpy-function that could simplify this. However you could wrap it as function so the complexity is hidden:
def put(arr, subarr, startidx):
    arr[startidx:startidx+len(subarr)] = subarr
    return arr

or with sequential indexing (not recommended):
def put(arr, subarr, startidx):
    arr[startidx:][:len(subarr)] = subarr
    return arr

You could also pad your mylist with NaNs:
np.pad(np.array(mylist, dtype=float),
       (2, 8-len(mylist)),
       mode='constant',
       constant_values=np.nan)

Comment: `np.pad` is a complex function that does a lot of concatenates.  And at the compiled code level, `concatenate` does the same sort of allocate and assign operation that the OP is trying to avoid.
Comment: sorry to ask about the "non recommended" one.. but it looks interesting. I never thought about it.. Why do not say is not recommended?
Comment: I think padding isn't really as performant, the other ones will be faster. I meant I wouldn't recommend the second approach becauseit just avoids the `startidx+` by adding a not-so-readable double slicing operation.


Stationary Observers Question

Question: An observer in a fixed location relative to our coordinate system has a worldline with constant $r, \theta, \phi$, and thereofre has four velocity $U$ with only the first component non zero. Because $U^aU_a=1$ and $U^0 >0$, the four velocity components are
$$U^0=\frac{1}{\sqrt{1-2m/r}}, \text{      } U^a=0 \text{ for a=1,2,3}$$
How has this been derived mathematically?
.... As in special relativity, the acceleration felt by the observer is $\sqrt{-\alpha_a\alpha^a}$
Where has the negative sign come from and why is it needed?
Comment: This question is more appropriate for the physics stack exchange page
Answer: The relation
\begin{equation}
U^0=\frac{1}{\sqrt{1-2m/r}}, U^a=0 \text{ for a=1,2,3}
\end{equation}
is obtained by solving the geodesic equation for the Schwarzschild metric
\begin{equation}
- d \tau^2=-(1-\frac{2m}{r}) dt^2+(1-\frac{2m}{r})^{-1} dr^2+r^2 d \theta ^2+ r^2 \sin^2(\theta) d \phi^2
\end{equation}
The Schwarzschild metric is a smooth spherically symmetric metric interpreted as the spacetime modelling the exterior of a spherically symmetric body of relativistic mass m. As a matter of fact, the angular dependence of the Schwarzschild metric is precisely the same as that of a sphere. It is therefore almost always sufficient to consider the equatorial plane $θ = π/2$, so that $dθ = 0$. In this coordinate system the metric is invariant under time translations,  and this allows us to define a  class of stationary observers whose world lines are given by constant values $r$, $\phi$ and $\theta$. Consequently, the lapse of proper time τ between two events at a fixed spatial point in Schwarzschild space-time is
\begin{equation}
ds^2 =-(1-\frac{2m}{r}) dt^2= -g _{00}dt^2=-d \tau ^2
\end{equation}
The element of proper time $d \tau$ is measured by a clock at the particular point, while the element of world time dt is fixed for the whole manifold. The 4-velocity of a stationary observer is $U = (U^0,0,0,0)$ with $U^0= dt/d\tau$. The acceleration of the observer is
\begin{equation}
\alpha^a= U^b \nabla_b U^a= U^b \left(\frac{\partial U^a}{\partial x^b}+ \Gamma_{bc}^{a} U^c \right)= U^0 \left(\frac{\partial U^a}{\partial x^0}+ \Gamma_{00}^{a} U^0 \right)=(U^0)^2 \Gamma_{00}^{a}
\end{equation}
Thus
\begin{equation}
\boldsymbol{\alpha}=(0,m/r²,0,0)
\end{equation}
The magnitude of the acceleration can be computed by using the dot product
\begin{equation}
\boldsymbol{\alpha} \cdot \boldsymbol{\alpha} = g_{ab} \alpha^a \alpha^b
\end{equation}
and then computing the square root. By doing that we have
\begin{equation}
|\boldsymbol{\alpha}|  =\left(1-\frac{2m}{r} \right)^{-1/2} \frac{m}{r^2}
\end{equation}
Since $g_{11}= -(1-\frac{2m}{r})^{-1}$ when defining $\sqrt{g_{ab} \alpha^a \alpha^b}=
\sqrt{-g_{11} \alpha^1 \alpha^1}$
we have to use the sign minus to be consistent with definition of  $g_{11}$.
For large values of $r$ this is essentially Newtonian, but as $r → 2m$, the acceleration becomes infinite.

Stationary Observers Question


Amazon EC2 instances changes server time/date on reboots and other time weirdness

Question: I have a windows instance up in EC2.  I manually set the timezone to Pacific.
1) For some reason using window's built in time sync doesn't work in the instance...but whatever. I turn off automatic time syncing...
but 2) On reboot the time on the server changes! For example, if i reboot it at 4PM on Wednesday, when the server comes back up it will read 12 noon on Thursday!
As a result any access to Amazon's other services like SImpleDB fail because the timestamps generated are too far off the current time.
Has anyone seen this or figured this out?
Answer: Go to this link on amazon's aws forum there is post by Nancy W. Abramson that might solve your problem. OR there is problem with AMD Hardware mentioned at blog.dt.org in time-and-clock-issues-in-windows-based-ec2-instances blog post. Hope this help you.


Log de transações de login MSSQL 2012

Question: Preciso de um help, tenho que disponibilizar um login no MSSQL a empresa do ERP e meu superior precisa monitorar as transações do tipo INSERT, DELETE e UPDATE que são feitas por eles, no caso os scripts que foram executados nesses tipos de transações.
Exemplos :
INSERT INTO tabela001 (id, campo1, campo2) Values (1,'Texto1', 123 )

No Log eu guardaria os dados do login, o tipo de transação e o script executado.
Comment: Fiz a pergunta, mas também não sei se é possível.
Answer: Acabei de responder uma pergunta semelhante aqui. Você pode trabalhar com triggers. Cada tabela no banco terá uma trigger para determinada operação (INSERT, DELETE E UPDATE). Através desta é possível obter a informação que você deseja e armazenar em uma tabela (sugestão).
Segue o exemplo de uma trigger do firebird:
CREATE TRIGGER au FOR table
  AFTER UPDATE
  POSITION 0
AS
BEGIN
  IF RDB$GET_CONTEXT('USER_TRANSACTION', 'MY_LOCK') IS NULL THEN
  BEGIN
    RDB$SET_CONTEXT('USER_TRANSACTION', 'MY_LOCK', 1);

    ...
    Do your update operations here
    ...

    RDB$SET_CONTEXT('USER_TRANSACTION', 'MY_LOCK', NULL);
  END

  WHEN ANY DO
  BEGIN
    RDB$SET_CONTEXT('USER_TRANSACTION', 'MY_LOCK', NULL);
    EXCEPTION;
  END
END

Comment: Vlw @Karan Alves Pereira, uma pena mas no SQL Server não funciona da mesma forma.
Comment: @RicardoSouza a criação da trigger para o sql server é bem semelhante. Acredito que você não terá dificuldades para criá-la. Qualquer coisa avisa. abraço.

Log de transações de login MSSQL 2012


AutoMapper doesn't work in asp net core 5.0.2

Question: I get an error which says I didn't register AutoMapper, but I did, and such configuration as listed below was used in another projects successfully:

System.InvalidOperationException: 'Unable to resolve service for type 'AutoMapper.Configuration.IConfiguration' while attempting to activate 'PromoAction.Services.Identity.API.Controllers.AccountController'

Please help me to figure out how to make it work in asp net core 5.
AutoMapperConfiguration.cs
public class AutoMapperConfiguration
{
   public MapperConfiguration Configure() => new(cfg =>
   {
       cfg.CreateMap<User, ClientDTO>();
       cfg.CreateMap<UserForRegistrationDto, User>()
            .ForMember(u => u.UserName, opt => opt.MapFrom(x => x.Email))
            .ForMember(u => u.FirstName, opt => opt.MapFrom(x => x.Name))
            .ForMember(u => u.LastName, opt => opt.MapFrom(x => x.Surname));
   });
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    var config = new AutoMapperConfiguration().Configure().CreateMapper();
    services.AddSingleton(sp => config);
}

AccountController.cs
public AccountController(IMapper mapper)
{
    this._mapper = mapper;
}

Comment: See following : https://learn.microsoft.com/en-us/dotnet/core/compatibility/5.0
Comment: AutoMapper works fine in .NET 5 -- they way you inject it is broken.
Answer: Recomended way of registering Autommaper is described in their docs: https://docs.automapper.org/en/stable/Dependency-injection.html#asp-net-core
Create mapping profile and register it using
services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);

In your case looks like you registered mapper instance, your example says that you injected mapper instance but exception says that you want to resolve IConfiguration. Check your code, if you don't try to inject IConfiguration (which is not registered).
Answer: The problem is that you are not injecting automapper in a good way.
follow the following steps:

Install the nuget package AutoMapper.Extensions.Microsoft.DependencyInjection

Create a new automapper profile inherited  from Profile class ( remember to add using AutoMapper), example:

 public class AutoMapperProfiles : Profile
    {
        public AutoMapperProfiles()
        {

            CreateMap<User, ClientDTO>();
            CreateMap<UserForRegistrationDto, User>()
                 .ForMember(u => u.UserName, opt => opt.MapFrom(x => x.Email))
                 .ForMember(u => u.FirstName, opt => opt.MapFrom(x => x.Name))
                 .ForMember(u => u.LastName, opt => opt.MapFrom(x => x.Surname));

        }
    }

In your startup class in the method configure services use AddAutoMapper and provide the typeof your startup
 services.AddAutoMapper(typeof(Startup));
After that you can inject it normally
public AccountController(IMapper mapper)
{
    this._mapper = mapper;
}


Controllers devem ter uma única responsabilidade?

Question: Assim como as classes e objetos de uma aplicação, meus controllers devem ter uma única responsabilidade?
Exemplo.
Tenho meu controller Cliente, que tem todas as relações com meu model Cliente.
Tenho também o model Contato.
Seria certo eu ter minhas actions ContatoPorCliente, ExcluirContatoCliente, etc. dentro do meu controller Cliente? Essas actions são chamadas na view Cliente.
Minha dúvida é por que as vezes temos telas que tem várias Abas(Tab) em um formulário.
Cliente que tem Contato, Dados Financeiro, etc...
Comment: Sim, isso sim, mas e quando há referencia de Contato com Cliente, aonde tu faz suas actions?
Answer: Não vejo problema em fazer isso, desde que os contatos referidos tenham alguma relação com o cliente, deixando explícito que são contatos de um cliente.
Caso existam outros caminhos, sem ser pela View de cliente, de manipular contatos, aí sim, eu acho que a separação se torna mais necessária.
Sabe, padrões de organização de código existem para ajudar a mover o ponto no projeto em que o código é feito... a separação de responsabilidades prevê uma necessidade que normalmente vem a tona durante a fase de manutenção (e que é um pesadelo): o acoplamento, então é melhor fazer um código com baixo grau de acoplamento desde o início.
Se contato for algo que existe somente como algo que faz parte do cliente, então o acoplamento não será alto de qualquer forma... caso contrário é melhor separar desde já.
Comment: Minha dúvida é por que as vezes temos telas que tem várias Abas(Tab) em um formulário. No exemplo que citei, contato pode estar por tudo, Cliente,Prestador, entre outras
Comment: No caso, acho que deve haver uma regra única. Se em cada aba podem haver itens que são agregados de cliente, e em outra existem itens que se relacionam com várias outras partes do sistema, aí eu prefiro já separar tudo. Um sistema com menos regras, e portanto mais simples, tem mais chances de sobreviver.


General equation of the line through the endpoints - derivation as value of "y"

Question: could you please tell me how this equation
$y={\frac {y_{1}-y_{0}}{x_{1}-x_{0}}}(x-x_{0})+y_{0}.$
was derived from "general equation of the line through the endpoints" below?
${\frac {y-y_{0}}{y_{1}-y_{0}}}={\frac {x-x_{0}}{x_{1}-x_{0}}}.$
I was just reading aboutBresenham's line algorithm on Wikipedia and came across this in the "Method" section of the article.
I've only started learning math and would be very grateful to see the steps to derive one from the other. Thank you.
Comment: Multiply both sides by $(y_1-y_0)$ then add $y_0$ to both sides.
Answer: So, first lets go over how we got $\frac{y-y_0}{y_1-y_0}=\frac{x-x_0}{x_1-x_0}$
Well, we know that the slope of the line from any two points must be the same.
So using this, we can say $\frac{y-y_0}{x-x_0}=\frac{y1-y0}{x1-x0}$, which we get from the slope formula. $(x_0,y_0)$ and $(x_1,y_1)$ are set points on the graph, while $(x,y)$ is any point on the graph.
We rearrange this to get the first equation we talk about $\frac{y-y_0}{y_1-y_0}=\frac{x-x_0}{x_1-x_0}$, and then we do algebraic manipulation to solve for y.
These are the steps:
$\frac{y-y_0}{y_1-y_0}=\frac{x-x_0}{x_1-x_0}$
multiply both sides by $y_1-y_0$
$(y-y_0)=\frac{x-x_0}{x_1-x_0}(y_1-y_0)$
since the order of multiplication and division does not matter, we can go ahead and write it as
$(y-y_0)=\frac{y_1-y_0}{x_1-x_0}(x-x_0)$
now the last step to isolate y is to add y0 to both sides
$y=\frac{y_1-y_0}{x_1-x_0}(x-x_0)+y_0$
and this is what they got :)
Hope this helped!!
Comment: More than helpful! Thank you.


nginx + IIS + GET

Question: I have nginx on pc "A" & IIS with ASP.NET on pc "B".
nginx is configured like this:
...
location ~ ((Web|Script)Resource.*)$ {
<code>            proxy_pass "B"/$1;
            proxy_redirect off;
            proxy_set_header REMOTE_ADDR $remote_addr;
            proxy_set_header REQUEST_URI $request_uri;
            proxy_set_header HTTP_REFERER $http_referer;
            #proxy_set_header  REQUEST_URI $request_uri;
            proxy_set_header  QUERY_STRING $query_string;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   Host $http_host;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    }...
</code>
but requests to
"B"/WebScript?a=b&c=d
aren't able to deliver GET data (a=b&c=d) to IIS part.
Could anyone help with this?
Edit:
There's some additional info:
nginx is also configured to proxy other data to Apache, running on "A" everything is fine there (at least GET is OK).
configuration is the same as above, but for different location
Comment: Does POST data work?
Answer: server {
listen       80;
  server_name  "B" URL; - - - - -For example here.myserver.com or www.myseaver.com
location / {
proxy_pass http://"B"intranet IP:port; - - - - -For example 192.168.1.101:80
proxy_set_header Host $host;

nginx + IIS + GET


Use the same function to validate 2 different questions

Question: I'm having an issue with trying to figure out how to use the same function (validate), to validate 2 different number inputs, using 2 different questions
int validate(int low, int high) {
    int flag = 0, number = 0;

    do
    {
        printf("Enter maximum value between %d and %d: ", low, high);
        scanf("%d", &number);
        if (number <= low || number > high)
        {
            printf("INVALID! Must enter a value between %d and %d: ", low, high);
            scanf("%d", &number);
        }
        else {
            flag = 1;
        }
    } while(flag == 0);
    return number;
}

Here is main()
int main () {
    int num1, num2;

    switch(menu()) {
    case 1:
    printf("~~~~~~~\n6/49 Number Generator\n");
    num1 = validate(1,49);
    num2 = validate(1, 6);
    break;
    default:
        printf("end");
    }
return(0);
}

When I call validate() the second time (returning num2), I need it to ask for a quantity of numbers.
Any help would be appreciated.
Comment: Your function is both doing input and validation (not validation alone).  Your input code should check that `scanf()` is successful; you have to decide what to do if it is not.  It isn't obvious why you are using asymmetric tests (`if (number <= low || number > high)`); using `<` would probably be more normal.  It is not clear what you mean by "I need to ask it for a quantity of numbers".  If you mean you need it to collect an array full of numbers, you need a second function that handles an array full.
Answer: If you are restricted to this function signature you can use internal static flag
Answer: Ideally your validate() should have another parameter signifying what it's gonna actually do.
Something like int validate(int low, int high, int type).
Then switch on type to do the various operations. But then I'd advise you to change the name of the function as validate would not be too appropriate. e.g. numGenEngine where type would signify step1, step2 etc.
Considering you need the function definition intact, you can use static variable.
int validate(int low, int high) {
    static int step = 0;
    int flag = 0, number = 0;

    if (step == 0) {
        // the first thing
    } else if (step == 1) {
        // the other thing
            // to reuse the function for the next set of operations
            // reset step to -1 here
    }

    step++;
    return number;
}


Finite Math Word Problem

Question: I have been having trouble with this word problem for a while.
A bicycle manufacturer builds one-, three-, and ten-speed models. The bicycles need both aluminum and steel. The company has available 50,075 units of steel and 62,160 units of aluminum. The one,-three, and ten speed models need, respectively, 10, 20, 25 units of steel and 24, 12, 30, units of aluminum. How many of each type of bicycle should be made in order to maximize profit if the company makes 2 dollars per one speed, 4 dollars per three speed, and 10 dollars per ten-speed. What is the maximum possible profit.
Company Aluminum = 62,160
Company Steel = 50,075
One-Speed Bicycle = 2 dollars, 10 Steel, 24 Aluminum.
Three-speed Bicycle = 4 dollars, 20 Steel, 12 Aluminum.
Ten-speed Bicycle = 10 dollars, 25 Steel, 30 Aluminum.
I would like to know how many of each type must be made to maximize profits, and what the maxiumum profit is.
Comment: @2012ssohn Note that my comment was made when this was on the Mathematica SE site, since the question has nothing to do with Mathematica. It may be fine for the Mathematics site.
Comment: This is not a site for math homework. It is for use of the program Mathematica.
Comment: Actually, asking homework questions is fine, and I think OP has [followed the guidelines](http://meta.math.stackexchange.com/questions/1803/how-to-ask-a-homework-question) ok. Also, [the Mathematica SE](http://mathematica.stackexchange.com/) would be the proper place to ask about using Mathematica.
Comment: Let $x,y,z$ be the number of $1,3,10$ speed bikes made.  How much steel does that take?  How much aluminum?  What is the profit?  You have gathered the data in the second paragraph, but not organized it into expressions.
Answer: Just to complement Ross' answer, I present the LPP formulation:
Let $x,y,z$ be the total number of one, three and ten speed bicycles manufactured respectively.
\begin{align}
\max_{x,y,z}\quad &2x+4y+10z\\
10x+20y+25z&\leq 50075\\
24x+12y+30z&\leq 62160\\
x,y,z &\geq 0
\end{align}

You can solve this using the Simplex Method.
If you aren't interested in the solution methodology and just want the answer, many commercial packages have the ability to solve such problems.
For instance, you can solve this in MATLAB using the following commands:
<code>c = [-2 -4 -10]
A = [10 20 25; 24 12 30]
b = [50075;62160]
linprog(c,A,b,[],[],[0;0;0])
</code>
which gives you the same answer as the one Ross described.
Answer: There are "official" techniques for linear programming problems like this, but with small numbers of equations one can do a lot by hand.  We have $50,075$ units of steel and $62,160$ units of aluminum.  The products have the characteristics: $$\begin {array} {}&1&3&10 \\ \hline Steel&10&20&25\\Aluminum&24&12&30\\Profit&2&4&10\\Profit/Steel&.2&.2&.4\\Profit/Al&.083&.333&.333\end {array}$$  With this data, the $10$ speed bikes are more profitable than either of the others per unit of each material, so we make as many of those as possible.  Based on steel, we can make $\frac {50075}{25}=2003$ and based on aluminum, we can make $\frac {62160}{30}=2072$.  If we make all those $10$ speeds, we use $60090$ aluminum and have $2070$ left.  Since neither of the other makes more profit per aluminum than $10$ speeds, it doesn't make sense to trade off some steel and make another model.

Finite Math Word Problem


Flatten data in one column and then copy rest of row cells to the new flattened column

Question: I have certain type of data :
Data Input
Now I would need to flatten the middle column to make each "size" into its own row but still copy the "info" corresponding to the correct "size" row, as displayed here :
Data Output that I need
I don't really know how to "copy" the information in the row to the new flattened rows, any ideas?
Comment: Any help on this one? I dont even think if anything like this is possible
Comment: share a copy/sample of your sheet
Answer: try:
<code>=ARRAYFORMULA(SPLIT(QUERY(FLATTEN(
 IF(B1:D="",,A1:A&"♦"&B1:D&"♦"&E1:E)),
 "where Col1 is not null"), "♦"))
</code>