Learning how to be a good rhythm guitarist before becoming a lead guitarist, where to start?

Question: I have recently been trying to hone in my improvisational skills. I'm stuck in the first position of the Am pentatonic box and can't move away from it. Whenever I try to move out of it, I randomize the next box that I go to, which most of the time leads to bad sounding improvisations.
I have narrowed the problem down to it being me having a bad sense of rhythm. I think I've got technique as a rhythm guitarist, but in regards to musicality, I don't.
I don't know which chords go together well, what goes after a chord, how minors, majors and 7ths are formed (don't know if this is important to be a good rhythm guitarist though), etc.
Answer: Your question covers several different topics but I think what you're interested in is Harmony. This is a very vast subject. As for the importance of what you lack as a rhythm guitarist, it largely depends on the style you play.
Lots of artists just don't know what they're doing when writing stuff and just happen to know empirically what goes well with what. In some styles like ska, punk or metal, a deep understanding of harmony is not mandatory, and learning a lot of tunes of this genre will give you a basic understanding of the underlying harmonies.
Scale Harmonization
The basis of understanding which chord goes well after another is known as scale harmonization. You don't need to know how to do it perfectly, just to do it once or two to grab the idea.
You should find many many tutorials, here's one.
Don't be deterred by the relative difficulty of it. Depending on how your brain is wired it might seem quite hard to do, but you won't need it on a day to day basis.
As a result of scale harmonization, for each note of the major scale, you've got a chord (major or minor). You can shuffle through each chord of the seventh, and it will sound ok.
In C, the chords are C, Dm, Em, F, G, Am, Bdim.
Now each one has a particular weight, a particular sound, or effect if you will, not only in association with the tonal center, but also to the previous and next chord.
For example, the degree I feels at rest, and most song will end on it. The V pushes the ear toward the I or the IV for example. Switching to the VI will go minor. For example a really cheesy progression would be I, IV, V. The bridge could go VI, III, V for example.
(this is a very basic explanation with lots of weakness but I think it's a good start).
There's a set of very common chord progressions. Some of them have even names (50's progression etc, I don't really know them in English).
What I like to do is learn the songs I like, and transpose them to C (for the sake of simplicity). Then I try to identify the chord progression. This way I can tell what I like about this changes. You can also tweak each chord in certain ways, some of them are done very frequently. There's rule for that, but you can just learn empirically (for example, you can play the IV and then the IVm, I've found this many Muse songs and I like the sound of it, so I use it in my compositions. But it doesn't work with the V for example :)
Attraction
To further describe the way each degree is attracted to another, let's take the V. The reason why the G7 (V) push toward C7M (I) is the following:
The seventh of G is F; its third is B.
The third of C is E; its root is C (obviously).
It means that two notes of the V chord are only one semi-tone apart from those of the I chords. A semi-tone interval is a very strong one, it is so close that the ear "wants" one chord to resolve to the other.
Extensions
If you try to do harmonization by yourself, you'll find that each chord has also a seventh, which can be major or minor. As for the other extensions (6, 11, 13 etc), this is also a very vast subject. Know that each degree of the harmonized scale may or may not be extended with each scale note.
Technique
For the technical aspect of rhythm playing, I would advise you to take a look at my answer to this related question.
On a side note, while I agree that rhythm playing is linked to your abilities as a lead player, it is still another topic and this will not necessarily solve your problems.
Answer: I think a good instinctive understanding of harmony is important, and one good way to get there is to work out chord progressions yourself.
Start with simple three-chord rock'n'roll standards. Assume that you're working with the root, the fourth and the fifth, and it's just a matter of working out which order to play them. Start in A, so you're working with really easy chord shapes: A, D, E. If you pick a song and realise it's got a fourth chord, put it aside and try a simpler song.
Forget about 7ths at first. Work out the root of the chord you're looking for (often listening to the bass part helps here), then work out whether it's major or minor, either just with your ears, or by reasoning about the scale you're in. For example, if you're playing in C, and the chord has a root of A, then it must be Am because there is no C# in the key.
To be more clear - take a song like "Blue Suede Shoes". I can promise you it can be played with three chords. Don't worry about what key the original is in. Have the lyrics written down, and make sure you know how it goes. Don't refer to tabs or chord sheets. Strum an A chord, and sing "One for the money...", and keep singing until your ear tells you that an A chord isn't right any more. Change chord. Experiment and use your ears to decide whether the next chord should be a D or an E. Keep doing that until you've got through the song.
Pretty soon you should be able to play chords for most three-chord songs in A on-the-fly. Even that's useful at parties! Now try it in other keys. C, D, E, F, G at least.
... and in parallel, start tackling those songs with more chords. You can still put songs aside if it becomes obvious that the chord structure is too complicated to tackle just yet. Build up to these things. With experience you'll be able to tell at first listen how complex the chord sequence of a song is.
It's fine to look at chord sheets when you're stuck, but try not to rely on them too heavily.

As for your improvisational skills, and getting out of the pentatonic box, try learning/copying the solos of people you admire. When they leave a box, think about why what they're doing works. Some people like to learn a variety of scales. Have a go at that.
Other people hear what they want to play, and play it, rather than play something in a scale and see what comes out. That's a great skill to have. Try singing a lick, then playing it -- trying repeatedly until you get it.  Then try singing in unison with your guitar, as you improvise. Sing what you want to hear, and try to play it at the same time.
Comment: So it's like playing the song without tabs nor chord books and then determining if whether the song only uses the chords A, D and E and through that I can pick up a sense of harmonization to it? Or did I misunderstand? Im sorry.

Aside from listening to the bass, can I determine the key/root of the song by just knowing which chord was first played for the entire song? Or could that be just categorized as an assumption?

Also after reading your answer I think Ive come to the conclusion that I don't even know what's the difference between a root of a chord and a key of a song. research time
Answer: I think there's some possibility for confusion of terms because lead and rhythm means different things depending on what precise area you're talking about.
In a rock band, there's usually a division between the rhythm guitar whose job is primarily harmony and chords (the left hand of the piano) and the lead guitar whose job is to play little melodies and solos (the right hand of the piano). You don't need to learn rhythm first. Rhythm isn't any less musical than lead playing. And playing lead well requires lots of rhythmic ability.
Definitely work on your rhythm-playing even if you don't intend to be a rhythm player. Many lead-guitar effects like syncopation and suspension require a keen rhythmic sense to accomplish. Sometimes a lead can be as simple as copying the rhythm part, replacing full-chords with power-chords, or replacing power-chords with dyads or just the root notes.

If you try to view the two guitarists as team whose job it is to play the song, then you can steer away from the view that the lead is more important and the rhythm should be delegated to the junior of the two. Rhythm and lead both have a function to serve and sometimes the rhythm is more important, sometime less important. Sometimes you gotta tell the soloist to chillax a few bars and let this groove breathe. The lead is the driver, but the rhythm is the horsepower.
And lead playing can be very rhythmic. Listen to some Louis Armstrong trumpet solos where he's just wailing the hell out of one note. But all the bending and wiggling is in rhythm.
Comment: thanks for the info, it does seem that my question is a little unclear. It's certainly the rhythm or the harmony part of my playing is the one I want to work on since I don't want to continue on relying on guess work when improvising or making random chord progressions.
Comment: now your edited answer was an eye-opener, I can't believe I still have this juvenile perspective on what lead guitarist/rhythm guitarist is. your answer cleared that off my mind.
Answer: I'm addressing only your first paragraph. Assuming you want to stay pentatonic for now, and know the box in A based around the 5th to 8th frets, this should help. The box below that has basically two notes per string, as the box you know. Each higher note on each string is the SAME note as the lower one in your known box.So you already know HALF of it !!  Guess what - the next box up uses for its bottom notes the same ones as the TOP notes of your known box. Thus you already know HALF of that one !!  So - in order to use all three boxes, you only need to replicate the pentatonic notes around frets 2/3  and frets 7/10. If you start the higher box on 6th string, 8th fret, and use the Am pent. notes, you'll hopefully realise that it's actually C maj. pent. you're playing. It happens to use EXACTLY the same 5 notes, so you can solo along regardless.
Comment: I can't quite grasp what you're trying to say here, but I think I read something related to your answer here [link](http://www.fretmeup.com/stuck-in-the-pentatonic-box/) or did I relate your answer wrongly?
Comment: Yes, quite similar. But I've tried to explain how shape 1 can be related to the shape (box) below it - towards the head of the guitar, and the box above - towards the guitar body. Also, I've covered all 6 strings rather than one octave, hopefully to give more scope to your playing. Grab your guitar and try to understand this, it'll make sense eventually !
Answer: There's a box of questions here, without a strong theme. I'll pick off what I can.

For most circumstances, the difference between a rhythm and lead guitarist is artificial, because most of the time, the lead guitarist is also playing behind a singer or other instrumental player. The number of musicians who only play lead and never have to support another musician is very small.
The way to work on your rhythm is to play rhythm. Turn on the radio and strum along to the songs. Mute the strings because the core here is rhythm, not harmony. Listen to the drummer and try to connect to that rhythm. If you can't connect to simple 4/4 pop/rock rhythms, there's no use trying to get to the more fun stuff. My rule here is: it is far better to play the wrong note at the right time than the right note at the wrong time.
For playing rhythm in an improvisational rock context, you don't really need to know the rules of harmony. In the rock context, certain jam bands to the contrary, you aren't improvising as rhythm guitarist, you're providing the stable foundation for the soloist to take off from, and improvising too much erodes that stability. You need to know the song as written by someone who knew the rules of harmony and obeyed them as desired. Eventually, once you see lots and lots of songs, you'll start noticing that songs that have G major, C major and D major often have Am and Em, and certain patterns. Knowing the rules of harmony is good, but to become a technically more proficient musician doesn't require that you know them yet.
The rules of harmony follow the rules of melody, and that's a bigger topic than can really be covered here. Certain genres follow different rules. Your Am box problem point to me that, playing leads, you're stuck to one pattern. There are many guitarists whose music I love who admit to never going far from that same pattern. I can say learn the scales, learn the modes. It wouldn't be bad for you to do so, but honestly, I'd say you can hold off until you're more comfortable with rhythm, know how to play the harmony part of a few songs, and can start to move that pattern around to different songs. Once you have that, scales and modes will make a lot more sense to you.
Comment: so it's all just about experiencing the harmonies per se you mean? Ill take on your suggestion of playing along with songs, I do that anyways, only problem I have is I do alot of guess work when determining what chords I am to use on a song, which I think means I just can't decipher chords by ear
Comment: Barre chords are the shortcut here. Even more to the point, "power". Root and fifth to start. The third gives you major and minor, and eventually you'll get to sevenths and sixths and ninths and thirteenths and diminished and augmented, but if you do the low two strings of barre chords, that'll get you the basics of finding out the chord structure.
Comment: Also, while you can throw chords together in all sorts of ways, be aware that popular music tends to use a few well-worn patterns. Look up "Axis of Awesome" on YouTube and you'll see now many songs are made up of root, fourth fifth and minor sixth.


Diferença entre funções de alta-ordem e primeira-classe

Question: Em linguagem funcional, qual a diferença entre funções de alta-ordem (high-order functions) e funções primeira-classe (first-class functins)?
Em JavaScript, qual seria a diferença entre esses dois tipos de funções?
Answer: Uma linguagem tem funções de primeira classe, quando funções podem ser
tratadas como valores que podem ser passados, manipulados, retornados...
ou seja, é possível operar funções. Este conceito é um atributo da linguagem,
ou ela tem ou não tem.
Função de alta ordem é uma função que recebe ou retorna uma função.
Só é possível definir uma função de alta ordem, se a linguagem tem
funções de primeira classe, pois é necessário que funções sejam "passáveis".
Este conceito é um atributo da função, ou ela é ou não é.
EDIT
Linguagens que não possuem funções de primeira classe, como o C, ainda assim
permitem a criação de funções de alta ordem, usando ponteiros de função.
Javascript é uma linguagem que possui funções de primeira classe, ou seja,
é possível passar, retornar e operar funções.
Referência:

Higher-order function(inglês)
First-class function(inglês)
Comment: O Java 8 possui algo parecido com Funções de alta ordem, que permite [referenciar funções](http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html).


How do I can get a clicked item to show/hide its hidden elements?

Question: I am having some trouble displaying a clicked items hidden elements.
Find below my clicked events code.
'click .stylishTiles'(event, instance) {
   event.preventDefault();
   var selectedTile = this._id;

   Session.set("selectedTile_id2", selectedTile);

   $("#hidden").show(300);
   $(".selected").addClass('show');
  },

'click .show'(event, instance) {
   event.preventDefault();

   $("#hidden").hide(300);
   $(".stylishTiles").removeClass('show');

}

The Session.set("selectedTile_id2", selectedTile) in the clicked event is passed on to the helper via Session.get('selectedTile_id2').
Find below the aimed helper code:
'selectedTile': function () {

    var selectedTileId = this._id;
    var selectedTile_id2 = Session.get('selectedTile_id2');

    if(selectedTileId == selectedTile_id2){
        return "selected"
    }
}

And find below the code for the targeted template:
<template name="invoicesV2C">

{{#each pendingInvoicesV2C}}

 KES: {{formatCurrency recipientAmount}}

 tel: {{recipientNumber}}
 purpose: {{invoicePurpose}}

{{/each}}

</template>

The {{#each pendingInvoicesV2C}} in the template correctly generates several items, while correctly hiding their hidden elements by default due to the CSS code
#hidden{
display: none;
}

The much desired effect is that I when I click on any item, its hidden elements, being:
 tel: {{recipientNumber}}
 purpose: {{invoicePurpose}}
 should show, hence
 $("#hidden").show(300);
 $(".selected").addClass('show');

And in reverse, whenever I click on an item already showing its elements,again being:
 tel: {{recipientNumber}}
 purpose: {{invoicePurpose}}
 it should be hidden.
Currently, regardless of the item I click on, only the first element in the list of items will show/hide its elements.
Kindly help me understand how I can get a clicked element to show its hidden details?
Comment: @ Michel Floyd Any help would be greatly appreciated
Comment: @jankapunt Any help would be greatly appreciated
Comment: @ Garmekain Anyhelp would be greatly appreciated
Answer: You have numerous errors along with really twisted logic.
Let me help you to simplify that:
CSS:
We're using class instead of id
.hidden {
  display: none;
}

Template:
<template name="invoicesV2C">
  {{#each pendingInvoicesV2C}}

        KES: {{formatCurrency recipientAmount}}

        tel: {{recipientNumber}}

        purpose: {{invoicePurpose}}

  {{/each}}
</template>

Template Code:
Template.invoicesV2C.events({
  'click .stylishTiles'(event) {
    event.preventDefault();
    const $e = $(event.target).closest('.stylishTiles');
    $e.find('.toggled').toggle(300);
  }
});

That's all. You don't even need helper and using Session at all.
Here is tiny fiddle, representing how it works: https://jsfiddle.net/iStyx/ff6hvorz/
Comment: Thank you for the prompt response, however the toggle() function doesn't seem to be working at all. I tried slightly altering the `$(event.target).closest('.stylishTiles')` to `$(event.target).closest('.stylishTiles').css({"color": "red", "border": "2px solid red"});` just to check if it actually picks up on the `$(event.target)`. It successfully turns the boarder red so thumbs up. I cant figure out why its not .toggle(300) isn't functioning. Any suggestions?
Comment: @SirBT Did you try the fiddle I mentioned? It's working there.
Comment: @SirBT Have a look at template I've posted, there is `toggled` class added to `` you want to show/hide. Did you add it?
Comment: Yes the fiddle works perfectly, however the toggle() in my meteor code doesn't seem to work...
Comment: Yes I added the toggled class to the  just as you suggested. Let me copy and paste, perhaps I missed something...
Comment: copied and pasted your template, still no difference
Comment: @SirBT But `.show(300)` and `.hide(300)` are working for you, right?
Comment: nope... I tried `const $e = $(event.target).closest('.stylishTiles').css({"color": "red", "border": "2px solid red"});
    $e.find('.toggled').show(300); ` but nothing shows
Comment: @SirBT Let me clarify, you don't really want animated show/hide, right? You just want to show/hide and that's all, correct?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/154592/discussion-between-sirbt-and-styx).


Using spanned images (.swm) with ImageX /ref switch

Question: I can't seem to find any working examples of usage of the /ref switch with ImageX. Can anyone provide known working syntax?
Answer: imagex /apply d:\image.swm /ref d:\image*.swm 1 c:
Comment: What if I have two files *.swm and one *.wim ?
What is the syntax? Or maybe I have apply to three times the same syntax changing only the file name?


How come you can hear individual notes but not overtones?

Question: In my understanding, all sounds are technically made from a combination of sine waves together that form a timbre, and as such any sound can be represented as a combination of sine waves. Let's take additive synthesis, for example, like this one:

In this case, multiple waves are added to produce a timbre, but you don't hear the overtones, just the tonic bass.
So why when, say with a guitar, a chord is strummed, do the notes not blend together and produce a single tone with overtones? Why is the brain able to pick out individual notes here but not in additive synthesis? (Obviously you COULD listen for only the overtones and potentially pick them out but it's not like a chord where it's obvious there's multiple tones.)
Answer:
In my understanding, all sounds are technically made from a combination of sin waves together that form a timbre, and as such any sound can be represented as a combination of sin waves.

That's one of the ways that we can think about sound waves - and due to the way the ear is built, it probably is the best way for your question.
From a survival point of view, our ear has evolved to tell us about 'things that happen' in the world around us.
When 'an event' happens in the world - for example, an eagle cries in the distance - we tend to get a group of sine waves...

That are related to each other by their frequencies being multiples of each other
That are related to each other by their volume envelopes coinciding.

...and this is what our auditory system is listening for to tell us that "something has happened".
Of course it's more difficult to separate events that occur together in time. But we can still do it - for example, if the ear hears components at
100, 157, 200, 300, 314, 400, 471, 500, 600, 628, 700, 785.... Hz,
Our auditory system is "clever enough" to tell that they are actually two sets of multiples - one set of multiples of 157, and one set of multiples of 100. So there are two notes playing - one with a fundamental of 100 Hz, and one with a fundamental of 157 Hz.
But it's not always that easy. What if we had two sounds playing that are related to each other in pitch? It would be much harder to separate out 2 notes that were 100 and 150 Hz for example, as some of their harmonics (such as at 300 Hz and 600 Hz) would be in common to both notes. And in fact, when composers create harmonies, this is often what they do - play notes together that have simple frequency relationships, such that the notes 'blend together' and create one sound.
So when you say:

why when, say with a guitar, a chord is strummed, do the notes not blend together and produce a single tone with overtones?

I don't quite agree with the premise of your question - actually, I think the notes in a typical chord do tend to blend together in a way that many people without musical training find difficult to separate. With a guitar it's perhaps slightly easier as the notes are typically struck at slightly different times when strummed, but when someone plays a chord on a piano, it is hard - without musical experience - to pick out the individual notes, especially if it's a big jazzy chord with more than 3 notes. With musical experience, we learn the 'feel' of particular combinations of notes, and can then do the reverse process of associating the 'feel' of a sound that we hear with a combination of notes. But it's certainly not something that everyone can do without practice.
In a way, you've put your finger on what harmony is - it's taking a number of sounds, each with their own sonic signature related to their harmonic structures, and putting them together in a way that you create another 'bigger' sound, with a more interesting (but often still coherent) harmonic structure. In a way, you could say that 'harmony' is the plural of 'timbre'!
It's probably worth mentioning a couple of simplifications that I'm making here:

When composers use an equal tempered scale, the frequency rations are often a little off from the kind of ideal simple ratio I referred to earlier
Many sounds contain partials and other energy at frequencies that aren't integer multiples of the fundamental.

... and yet our ears cope with this too.
Comment: Also look up Tartini tones (multiple videos on Youtube). This is a phenomenon where multiple pitches played at the same time produce the illusion of a lower note, because your brain thinks that the two real notes are overtones of the same nonexistent fundamental.
Comment: Pipe organs use this resultant to create the effect of a 32' or 64' stop: "For a 32' stop, the two ranks are 16' and 10-2/3'; for a 64' stop, the two ranks are 32' and 21-1/3'. This effect was first used in the organ by Abt Vogler (1749-1814)." --http://www.organstops.org/r/resultant.html
Answer: With training you can actually hear the overtones. A good introduction to this is listening to polyphonic overtone singing. This is a singing technique in with the overtones of the voice are amplified by creating a 2nd resonance chamber in the mouth with tongue positioning.
Here is an example of that:

From listening to that you should know what they sound like, and then listen to a constant pitch and try to pick out the overtones. Once you notice them it's kind of hard to unnoticed them. I hear overtones in almost every steady pitch now.


Css, js and images get partially downloaded with Netscaler

Question: Trying to sort this out with our Netscaler provider but they have issues finding the problem for this aswell so asking her to see if anyone have any input on where to start looking.
We have Netscaler as an SSL offload handling traffic into our IIS site running on http. After an security upgrade of Netscaler we are experiencing quite a lot of loading errors of css, js and images. They get cut of while loading. In Firefox I get no clear error but looking at what has been transferred I can see that only part of the file has been downloaded even if it's Status 200. Same with images that are partially loaded showing only the top of the image.
In Chrome I get net::ERR_HTTP2_PROTOCOL_ERROR 200 but can't see any more details about it.
It only affects some of the files but it's always css, js or image files that get this error and most of the time it's the same files. So it fails to load some files but loads other of same type just fine. Reloading the page sometimes fix the problem only to occur again on some of the next loads.
Googling the Chrome error doesn't give much so does anyone have any clue on what to go next in trying to debug this error?
Update: This is the current settings for http2
netscaler http2 configuration
Update 2: The issue has now been resolved and apparently the Netscaler version 12 had some Http2 issues since they came out with a patched version (12.1) the day after the upgrade was applied to our Netscaler. Took a little bit too long for our Netscaler consultant to see that unfortuanately so the issued were affecting us for unnecessary period of two weeks. Accepting Jans answer since the last comment was to upgrade to latest version.
Answer: Getting the obvious out of the way:
- Are your browsers up-to-date?
First things to look at on the NetScaler:

Is IC (Integrated Caching) enabled? If so, try disabling it and try again?
How is the HTTP-protocol configured?
Hos is SSL configured.

It might be due to incorrect HTTP/2 settings:

System --> HTTP parameters: is HTTP/2 Server-Side enabled or not?
Try configuring a HTTP profile under System --> Profiles --> HTTP?

If you want, I can have a quick look along with you too troubleshoot this.
Kind regards,
Jan
Comment: Yes latest versions of Chrome (78.0.3904.70) and Firefox Developer (71.0b3). Unfortunately this Netscaler is a shared setup and only managable by our consultant. I will pass the information to check these settings to them. As I understand the upgrade that was made was from Citrix Netscaler to Citrix ADC but have no clue what that means
Comment: The frustrating part is to understand the problem. Like what causes the browser to stop downloading certain resources int the middle of the transfer?
Comment: I get it, no problem. Well, if it ain't caching, it ha to be in the http-profile containing the http/2 settings. Buffers are used to collect and send data over the wire, it is probably going wrong somewhere in that part, which explains why you still get a part of the image.
Comment: You could advise them to upgrade the NetScaler to a later build (if it isn't on the latest one)


Segmentation fault in NASM 64bit

Question: I am trying to output the result to the user after getting 3 inputs from scanf.
When I run my code, I am able to get the input I need. However it crashes after I collect the input and begin the calculation.
By the way, I am using Ubuntu 14.04 with g++ and NASM 64bit.
Here's how it should look:
This program is brought to you by Chris Tarazi

Welcome to Areas of Trapezoids

Please enter one of the base numbers: 5.8

Please enter the other base number: 2.2

Please enter the height: 6.5

****//Crashes here with Segmentation fault (core dumped)****

The area of a trapezoid with sizes 5.799999999999999365, 2.200000000000000153,
and 6.500000000000000000 is 26.000000000000000328

Have a nice day.  Enjoy your trapezoids.

C++ file:
#include <stdio.h>
#include <stdint.h>

extern "C" double ComputeArea();    // links with global in assembly

using namespace std;

int main()
{
    double area;

    printf("This program is brought to you by Chris Tarazi.\n");

    area = ComputeArea();

    printf("Have a nice day. Enjoy your trapezoids.\n");

    return 0;
}

Assembly file:
extern printf                                               ; This function will be linked later.

extern scanf

global ComputeArea                                          ; Declare function global to link with "extern" from C++.

;---------------------------------Declare variables-------------------------------------------
segment .data

welcome:                           db "Welcome to the area of trapezoids.", 10, 0

input:                             db "Please enter one of the base numbers: ", 0

secInput:                          db "Please enter the other base number: ", 0

output:                            db "The area of a trapezoid with sizes %1.18lf, %1.18lf, and %1.18lf is %1.18lf .", 10, 0

hInput:                            db "Please enter the height: ", 0

inputformat:                       db "%lf", 0

stringformat:                      db "%s", 0

fourfloatformat:                   db "%1.18lf  %1.18lf  %1.18lf  %1.18lf", 0

;---------------------------------Begin segment of executable code------------------------------
segment .text

ComputeArea:                                                    ; Area of trapezoid = ((a + b) / 2) * h.

    push       rbp                                              ; Save a copy of the stack base pointer
    mov        rbp, rsp                                         ; We do this in order to be 100% compatible with C and C++.
    push       rbx                                              ; Back up rbx
    push       rcx                                              ; Back up rcx
    push       rdx                                              ; Back up rdx
    push       rsi                                              ; Back up rsi
    push       rdi                                              ; Back up rdi
    push       r8                                               ; Back up r8
    push       r9                                               ; Back up r9
    push       r10                                              ; Back up r10
    push       r11                                              ; Back up r11
    push       r12                                              ; Back up r12
    push       r13                                              ; Back up r13
    push       r14                                              ; Back up r14
    push       r15                                              ; Back up r15
    pushf                                                       ; Back up rflags

;---------------------------------Output messages to user---------------------------------------
    mov qword rax, 0
    mov rdi, stringformat
    mov rsi, welcome
    call printf

    mov qword rax, 0
    mov rdi, stringformat
    mov rsi, input
    call printf

    push qword 0
    mov qword rax, 0
    mov rdi, inputformat
    mov rsi, rsp                ;firstbase
    call scanf
    movsd xmm0, [rsp]
    pop rax

    mov qword rax, 0
    mov rdi, stringformat
    mov rsi, secInput
    call printf

    push qword 0
    mov qword  rax, 0
    mov rdi, inputformat
    mov rsi, rsp                ;secondbase
    call scanf
    movsd xmm1, [rsp + 4]
    pop rax

    mov qword rax, 0
    mov rdi, stringformat
    mov rsi, hInput
    call printf

    push qword 0
    mov qword  rax, 0
    mov rdi, inputformat
    mov rsi, rsp                ;height
    call scanf
    movsd xmm2, [rsp + 8]
    pop rax

;---------------------------------Begin ComputeArea Calculation-----------------------------------

    mov rax, 2
    cvtsi2sd xmm3, rax

    addsd xmm0, xmm1
    divsd xmm0, xmm3
    mulsd xmm0, xmm2

    ret

;---------------------------------Output result to user-------------------------------------------
    mov rax, 3
    mov rdi, output
    call printf

Comment: Why not write this in C++ and just have the compiler generate the assembly ;isting?  Then with the assembly listing compare what you're doing now with the generated assembly code.
Comment: Don't you need to pop those pushed rbx, rcx... before 'ret'?
Comment: Aside from comparing with the output of a compiler, this should be pretty easy to debug with a debugger or disassembler.
Comment: @user657267 I am new to Assembly programming so these tools and utilities are all new to me as well. What could I use to debug the program?
Comment: @ChrisTarazi [this](http://stackoverflow.com/questions/2420813/using-gdb-to-single-step-assembly-code-outside-specified-executable-causes-error) might help.
Answer: First off, why on earth are you saving ALL of those registers?!?  The ABI for 64 bit Linux says you only need to save rbx, rbp, and r12 - r15 if you use those registers in your function.  Also, you using Assembler, there is no need to create a stack frame in 64bit land (plus you aren't even using rbp! so why create a stack frame?)  The only thing that is very important is to make sure your stack is aligned on a 16 byte boundary - call pushes an 8 byte return address, so all you need in your ComputeArea function is sub rsp, 8 and add rsp, 8 right before your ret.
In your first scanf you are using rsp without adjusting it, you just overwrote something!
You do some computations here:
mov rax, 2
cvtsi2sd xmm3, rax

addsd xmm0, xmm1
divsd xmm0, xmm3
mulsd xmm0, xmm2

ret

You return from the procedure here but do not pop all of those registers you just pushed!!  So basically your stack pointer is all messed up!  The CPU does not know what the return address is!
What you do in the prologue, must be reversed in the epilogue before you return!
Maybe, you should start simple, read in 3 floats and try to print them!
When I correct your code, this is my output:
Welcome to the area of trapezoids.
Please enter one of the base numbers: 5.8
Please enter the other base number: 2.2
Please enter the height: 6.5
The area of a trapezoid with sizes 5.799999999999999822, 2.200000000000000178, and 6.500000000000000000 is 26.000000000000000000 .

Comment: My professor assigned this as a summer assignment so he basically threw us into a fire. I'm not sure what a stack frame is and how I used one. I'm not home at the moment but thank you for posting, I'll let you know how it goes when i get home.
Comment: I've fixed everything else (no more seg fault) but I still can't get the output to show?

Segmentation fault in NASM 64bit


Exclusive lock at Hive Table has not got released automatically when hive services restart in between

Question: While running Insert command INSERT INTO TABLE xyz PARTITION(partition_date='2020-02-28') values('A',123, 'C',45)..... or Alter table drop partition (alter table  xyz  drop if exists partition(partition_date='2020-02-28'); command in hive, if hive services got restarted in between through ambari or due to any unwanted scenario, then that acquired the exclusive lock on that partition which will remains after the restart also and for that kind of job there is no yarn application id is generated sometimes and if generated then it also got succeeded but exclusive locks remains on that table or partition, which later we have to manually released from the table or partitioned.

So why these locks remains on that partition or table and how these kind of scenarios can be handle at our end?
Is there any workaround for these kind of scenarios?
Comment: Locks may be left dangling in ZooKeeper case of crash, or because of a bug. This happens. Solutions: (1) wait until they expire -- cf. https://cwiki.apache.org/confluence/display/Hive/Configuration+Properties#ConfigurationProperties-Locking for how to tune the lifetime of a lock (2) remove the locks manually in ZooKeeper when needed (3) disable the locking mechanism altogether, if you want to live dangerously (Spark and Impala and Presto don't care about locks anyway so the danger is already there)
Comment: You can run any number of HS2 instances in parallel _( High Availibility is achieved via an active/active setup)_. An instance cannot remove existing locks on startup, because they might be used by other instances -- which makes automatic cleanup impossible.
Answer: I met a similar problem and resolved it, there are two ways:
(1) The hive lock information is stored at a mysql table called hive.hive_locks, so you can delete relevant rows about your sql table, or truncate that table. But this way cannot fix the problem permanently.
(2) Add a configuration in hive-site.xml, just like this:
<property>
    <name>metastore.task.threads.always</name>
    <value>org.apache.hadoop.hive.metastore.events.EventCleanerTask,org.apache.hadoop.hive.metastore.RuntimeStatsCleanerTask,org.apache.hadoop.hive.metastore.repl.DumpDirCleanerTask,org.apache.hadoop.hive.metastore.txn.AcidHouseKeeperService</value>
</property>

You can also refer to the answer on this question, i made a detailed explanation about the second way:
https://stackoverflow.com/a/73771475/9120595


Can you use jQuery to display a view?

Question: I want to do something similar to views slideshow. The thing is my javascript is written already. I would like my javascript to be able to be integrated within the drupal framework from views. The JQuery just is a simple image slideshow like this one here.  I just would prefer that I could show all or specific view field content instead of putting in the url in the javascript the long way. I want these images to come directly from a content type. Can you show me how?
Comment: Being a newbie doesn't justify to write confusing english :) okay i'm not a native speaker, but i still don't get what you actually want.
Comment: @DanielWehner, +1
Answer: You could create a small module that will be called through ajax:
<code>function MYMODULE_node_menu() {
    return array(//$items
        'MYMODULE/%' => array(
            'page callback' => 'MYMODULE_display_view',
            'page arguments' => array(1),
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        )
    );
}
function MYMODULE_display_view($view_name) {
    // display your view depending on $view_name
   $view = views_get_view($view_name);
   $view->execute();
   echo $view->render();
}
</code>
Get a views html by making an ajax call using jQuery:
<code>$(document).ready(function() {
   $.ajax('MYMODULE/YOUR_VIEW_NAME', {
           sucess:function(data) {
              // data will contain the html for your view
           }
   });
 });
</code>
You might find the following Drupal 7 Advanced Ajax helpful.
Comment: Thanks for the link to the slides. Didn't know about it. It should be on d.o.

Can you use jQuery to display a view?


What is the best way to break using the pedal too frequently?

Question: I have been playing piano on an 88-key electric piano a fair bit recently. I have developed what I believe to be a very bad habit, in that I use the sustain pedal very often.
While I don't think this is always wrong it means I can be very sloppy and slow on my finger movements since I am preventing a dead time between different chords/notes (because the sustain pedal is becoming a crutch, see this comment).
What is the best way to break this habit? Should I just disconnect the sustain pedal (it'd be one way!)? I have a hugely negative reaction to this because I dislike how choppy everything sounds.
Comment: Tape your foot to the floor :-)
Comment: Is this an actual electric piano (e.g. Fender Rhodes) or could you be misusing the term to refer to an electronic "piano" (a simplified synthesizer keyboard with built in speakers, repackaged as a piece of furniture)?
Comment: If everything sounds choppy on a synthesizer piano patch, that suggests that the patch has a poorly tuned release time. Release time is the decay of a note which takes place when you release the key. When release time is too fast, you will have a sensation that your technique is choppy. Phrases do not "flow". Needless to say, this type of parameter is not accessible in electronic pianos.
Comment: @Kaz there is a 99% chance the problem is me, not the keyboard itself... :)
Comment: Disconnect the pedal, or put a box over it so you can't engage it.
Comment: Play an key instrument without pedals. Organ, Hapsichord, Cembalo, and you will learn to listen what a sound is like without "cheating" it. The pedal is used to often to cheat hard passages, instead of just enriching the sound.
Answer: Find a reasonably well maintained real piano, and play it without using the pedal for a while.
If you find a real piano OK
If you find that the real piano doesn't have the choppiness you're experiencing on your electronic piano, then the problem is the piano sound on your keyboard.
Specifically, it's the release property of notes that is significant. That's what happens when you let go of the key. On a real piano, it takes time (not very much!) for the damper to reach the string, and the string continues to vibrate (although not for long) as the damper mutes it. Any simulated piano must simulate this effect.
There might be a better patch you could choose -- but I imagine you'd have already tried that. Unfortunately the other alternatives are to buy a MIDI sound module containing a better piano sound, use a computer as a sound module, or buy a whole new keyboard. All of these involve spending money.
If you find a real piano has the same problem
If you find the real piano choppy too, then it's likely that the problem is with your technique. You might be playing every note staccato, and masking it with the sustain pedal.
In this case, disconnect your sustain pedal (to avoid temptation) and concentrate on keeping your finger on each key for longer. Try playing the same part staccato, normally, and legato.
Piano exercise books contain exercises that target continuity. Try some of these, or ask a teacher for direction.
Once you've nailed this, re-attach the pedal - it's a perfectly valid tool in many situations.
Answer: There are 2 different ways of using the pedal on a keyboard instrument.

You're unable to do a proper legato between notes and you'll cover it with some pedal.
You use it because you think it sounds better.

The boundary between these two approach is slight but it exists. Let me give you some examples.
Most '800 romantic music is supposed to be played with a good dose of pedal (see Debussy, Schumann and probably many other which I've not played so I won't touch). If you try to play it without, some passages just sounds awful: they're impossible to be interpreted properly with 10 fingers and no pedal.
On the contrary, Bach music is not supposed to be played with a pedal at all (opinions are conflicting but it is widely accepted that the pedal usage should be really limited when playing cembalo music on the piano). Still, if you adopt this approach you'll have a very hard time trying to cover up some passages (but it is not impossible).
If you play Bach you'll notice that ALL of his music is supposed to be played by 10 fingers but not necessarily a pedal: the only way to correctly interpret this music is with a proper fingering.
Here, look at this snippet of Bach partita in E minor:

It would be very tempting to play that descent of 6th in the second beat with just one hand and cover the staccato with some pedal (or just not cover it at all). This would create a gap between each one of those descending 6th which would sound like a staccato.
How would you cover that? Pedal? That's what an amateur would do. Check the great pianists:

Gould, minute 2.55
Murray, minute 2.40

Do you hear any gap? Nope. Do you hear any pedal? I don't. So, how do they do that? Proper fingering. If you notice, the right hand has a very simple theme to play: why not use some free fingers from the right hand to "help" the left hand? The first time I was trying to do that my brain exploded but everything which is possible can be learned. For example it is impossible to play a progression of 6th with one hand without gaps or finger substitution.
There are thousands of these little "problems" in Bach music and all of them may be overcome only with proper fingering (and by leaving the pedal).
Now, let's move on to another repertory. Here, listen this classic: Debussy, Claire de Lune. Could you even try to imagine this piece without a pedal? If yes, you're either mad or deaf.
If you want even a more extreme example of something which cannot be played without a pedal, why not listen a piano transcription of one hugest and most magnificent orchestration of all times? Wagner for piano. You can't possibly play that without a pedal: I'm still wondering how you can play that with just 2 hands, let alone without a pedal...
Straight back to question, I hope you'll understand that is impossible to answer it without a reference to a particular passage/piece of music. However, since you're concerned about using the pedal too much a very general piece of advice which helped me is: when approaching a new piece of music, keep the foot away from the pedal. Totally.
Try to let it sound good without the pedal: if you need to blend the notes in a well-sounding legato just try a more wise fingering.
When you'll find a gap or an aesthetically unpleasant passage, you'll eventualy be ready to use the pedal to cover it up but please... Make sure you've studied without the pedal before.
Answer: As slim suggests, try a real piano - it may be that the sustain on yours is not as good as that on a proper piano.The 'mechanism' is rather different from acoustic to electric/electronic piano.
Slow everything you play down to 1/2 to 1/4 speed, and listen to the 'choppiness'. If it's still there, you need to address your style of playing note to note.With full chords, we need to use the pedal to provide continuity between each chord, but single note tunes should be made to flow without resorting to pedalling. Slowing down will allow you to move smoothly from note to note - it's like speaking - you don't start the next word till you've finished the last, but conversely, you don't leave gaps in between the words (until you come to a full stop or comma).
Answer: Whenever you use the pedal, you're balancing clarity of tone with the lushness of the piano's sound. In some music, such as Debussy's works, it's entirely appropriate to use lots of pedal, because you want that lush sound. In others, such as much of Bach's works, you would not want it, because the clarity of the counterpoint is often more important.
To further muddy the waters, the question of how much pedal you use is piano-dependent. My electric keyboard's pedal does not sustain notes as long as my acoustic piano's does (and I think this is actually billed as a feature!). As such, I use more pedal on my keyboard than I do on my piano. Even among acoustic pianos, some resonate more than others. Some baby grands may be so muddy in the bass registers that you simply cannot use any pedal at all when you're playing down there. That same part on a concert grand may be fine with pedal full tilt. A piano in a practice room will have a different resonance than the same piano in a concert hall. Hell, that piano in an empty concert hall has a different resonance than the same piano in a full concert hall! All of these situations require the pianist to approach the piece differently; a different touch on the keys, a different set of dynamics, and different use of the pedal. The question isn't "how much are you using the pedal", it's "how clearly are you playing?"
In my book, you're using the pedal as a crutch when in the process of getting a better legato, you compromise the clarity of your melody. In that case, just use less pedal. It helps to get a clear idea of what you want your melody to sound like. So play it without pedal, using whatever fingering gives you the sound you like best. Use both hands if you have to. But get the sound you want out of the piano without pedal. Then, add in the other parts. If/when you lose the sound you're looking for, use the pedal to help. Use it like a third hand; you don't use your hands to hold the notes forever, just long enough.
Answer: I would also like to add that playing with the pedal is not really that bad.  I would argue that there are very few circumstances where you specifically have to avoid the sustain pedal, as long as you use it well.  This is tough when soloing or playing runs because you have to be quick and accurate with your foot, but this could be a time that certain players would choose to not constantly use the pedal.  I would argue that with good foot work the only time to strictly avoid the pedal is when you don't want the un-dampened strings to vibrate, which will tend to fill out the sound and make it brighter.
Fair Warning: I play a lot of piano but am not a performer on the instrument.  Likewise, I've taken lots of lessons but not to an incredibly advanced level.


How do I write the contents of a SecureString to the Response stream?

Question: In an Asp.net MVC 5 application I have a SecureString being passed into my view via the model. I would now like to write the contents of that SecureString to the Response stream without having to convert it to a string first. How can I achieve this?
Comment: Using a SecureString in an HTTP context doesn't make any sense. The class is only there to prevent the string from being in your application's memory in plain sight. As soon as you want to transfer it over HTTP, it _must_ become a plain string.
Comment: The .NET HTTP API doesn't provide this. The only entrance you have to the HTTP response body is in the form of a plaintext stream, in which you have to write the strings or bytes that you wish to transmit. So in order to write them to the response, they must be plaintext.
Comment: In a web application, there are so many attack surfaces, using SecureString is like closing the window while the door is still open with a neon sign illuminating the way.
Comment: I am aware that there will be no such thing as 100% security, but I would like to reduce the attack surface as much as possible. Hence I am passing the data around as a SecureString inside my application and now that I actually need to show it to the end user I want to write it directly to the Response stream, rather than convert it to a string first and write that to the stream.
Comment: _How do I write a SecureString to the Response stream?_ - Encrypted.
Comment: Assuming I am already aware of all of this but still need to do it, is it possible? How do I write the contents of the SecureString to the Response stream one byte at a time (knowing full well that each byte and the stream are plain text).
Comment: @HenkHolterman I like the idea of encrypting the contents of the SecureString. Can you suggest a way of achieving this so that it never exists as a plain text string and so that I can decrypt it client side via Javascript?
Comment: You can't get data out of a `SecureString` other than calling `ToString()` (or [`Marshal.SecureStringToBSTR()`](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.securestringtobstr%28v=vs.100%29.aspx)). This will create the unencrypted string in-memory again. As for your encryption: you'll be sending the cyphertext _and_ the key over the same channel, effectively nullifying the purpose.
Comment: Calling 'ToString()' on a 'SecureString' does not give access tot he contents of the 'SecureString'! And 'Marshal.SecureStringToBSTR()' gives a 'pointer' to a binary string record NOT a 'string'! 'Marshal.SecureStringToGlobalAllocUnicode' seems like a better choice, but I then would rather get each byte individually rather than having to call 'Marshal.PtrToStringUni()'. Any ideas?
Answer: This is the HtmlHelper extension I have come up with. I am sure it can be improved, but it achieves my goal of writing a SecureString to the Response stream without it ever being represented as a string.
<code>public static class SecureStringHelpers
{
    public static void WriteSecureStringToResponse(this HtmlHelper helper, SecureString secureString)
    {
        if (secureString != null)
        {
            IntPtr unmanagedString = IntPtr.Zero;

            var secureByteArray = new byte[2];

            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);

                var offset = 0;
                var endOfString = false;

                do
                {
                    secureByteArray[0] = Marshal.ReadByte(unmanagedString, offset);
                    offset++;
                    secureByteArray[1] = Marshal.ReadByte(unmanagedString, offset);
                    offset++;

                    if (!(secureByteArray[0] == 0 && secureByteArray[1] == 0))
                    {
                        helper.ViewContext.Writer.Write(System.BitConverter.ToChar(secureByteArray, 0));
                    }
                    else
                    {
                        endOfString = true;
                    }

                } while (!endOfString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
                secureByteArray[0] = 0;
                secureByteArray[1] = 0;
            }
        }
    }
}
</code>


Performance and Field Collection

Question: I have a use case where I want to add multiple fields grouped together to an entity, field collection is perfect for this and I have it working well now this way.
Field collection stores all field collection entities in one table in field_collection_item, so if I had another field collection that had a huge number of rows would it effect performance? If so then I would like to store these other fields groups somewhere else, maybe an entity reference so these fields are in their own table. How would I convert my field collection to entity reference.
Can I duplicate the functionality of field collection with entity reference? As essentially an entity reference and field collection are the same. But if I had an entity reference it would be in it's own table that is less crowded.
Answer: Not exactly. Field Collection main purpose is to make a field that holds other fields so the data can be logically grouped. So, no, you can't really "convert" it to an entity reference field - they store different data. An entity reference points at another entity; so you'd need an entity to be a container for that data. You can either achieve this via Entity API, or use ECK. I suppose you could write a migration/batch script to port over the data, but I really don't see the point unless the entities were going to be viewed on their own page.
You shouldn't have any issue with the number of rows in the database, the issue will arise when it comes to operating with that data. If you have an entity that has 1500 field collection items, and you load them for display, yes, you will have very severe performance issues. Think of it like calling entity_load 1500 times.
This usually rears its ugly head when you try to make some Views to display field collection items. Pro tip there - disable automatic preview in the Views config.
Here are some resources that may help:

https://drupal.stackexchange.com/a/105397/57
https://www.computerminds.co.uk/drupal-code/you-should-use-entity-cache
https://blog.openlucius.com/en/blog/drupal-field-collection-vs-drupal-compound-fields

This thread also has some good history on a group of people looking for performance improvements with Field Collections: https://www.drupal.org/node/1268620
Edit:
Forgot to link to Entity Cache, which you can bolt on to Field Collection.
In the past, I had came up with two solutions to solve performance bottlenecks revolving around Field Collection.
In one case, I would prime the cache with a nightly cron run, render the field collection field into a variable and cache that variable. If the cache item exists, I pass that as the template variable. This bypasses loading and rendering the field and rendering the data (entity_load) for every user requesting the page.
This works, until your cache item grows to over 1MB in which case it can still cause MySQL to slow down. You may also want to look into adding Memcache or Redis on top as the caching backend to alleviate that. Ultimately, MySQL will be your bottleneck - so you should try to offset that work and cache as much as possible in a caching backend.
In another case, I wound up storing the data in Solr. When the node was preprocessed, I would query Solr for that item. I was also storing the rendered result in Solr, so that my result already contained the rendered HTML. This was the fastest solution for end users, but came with a bit of work to keep it up to date. This is also beneficial if you also have to search through that data elsewhere, since you'd already (read: should) be working with Solr in that case.
Comment: What about creating a new entity with ECK with all the fields from Field Collection on it and using and Inline Entity form to create the container?

Performance and Field Collection


Solving Triangle Word Problems

Question: A ship leaves port for a remote island 34 miles west and 60 miles south of the port. Find the distance and bearing to the remote island.
What would the diagram look like to this problem? and what would the bearing be?
Answer: The diagram would look like a right triangle.  One leg has length 34 pointed left.  From the end of that, the other leg points down with length 60.
Comment: Okay that's what I thought and how would I find the bearing?
Comment: You find the bearing with an arctangent function.
Comment: Okay thank you very much!
Answer: The answer would be $68.96$ after using Pythagorean theorem ($a^2+b^2=c^2$).
$$ \sqrt{4756}\approx 68.96.$$

Solving Triangle Word Problems


Duvida sobre a Classe Context

Question: No meu sistema tenho a classe Context para fazer a conexão com o Banco, através do Entity Framework e estou com uma duvida, só devo usar o public DbSet<NomedaClasse> Classe {get; set;} se eu estiver fazendo meu sistema pelo padrão Code First ou posso usá-lo normalmente? Desculpe a pergunta, sou novato em programação!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Entity;
using CadastroAtivos.Models;

namespace CadastroAtivos.DAL
{
    public class clsContext : DbContext
    {
        public clsContext() : base ("name=Stringconexao"){}

        public DbSet<clsMarcaModel> dbMarcas { get; set; }

        public DbSet<clsModeloModel> dbModelos { get; set; }

Comment: O que é usar normalmente? porque sempre deve usar normalmente, nunca irregularmente. Se você é novato em programação deve começar aprender primeiro os conceitos básicos, os fundamentos, para poder entender o resto. Embora possa parecer que está conseguindo fazer algo, sem entender tudo o que está acontecendo ali desde sua base pode estar fazendo tudo errado e nem tem condições de se dar conta dos erros. Não existe novato mexendo com EF, pelo menos não com propriedade, então é melhor voltar alguns passos antes.
Comment: Você pode configurar um Context e aponta-lo como chave unica de conexão no seu web.config
Answer: DbSet<T> são a interpretação por meio de objetos das tabelas do seu banco de dados, independente de como foi a abordagem da implementação do seu contexto, seja ela Database First ou Code First.
Caso ainda não conheça o suficiente de EntityFramework, procure entendê-lo melhor acessando a documentação do Entity:
http://www.entityframeworktutorial.net/what-is-entityframework.aspx
Answer: No caso de um EF Database First, também existe um contexto, que é gerado e atualizado automaticamente toda vez que você atualiza o modelo do EDMX.
Comment: Desculpa a pergunta, o que seria EDMX?
Comment: EDMX é um arquivo XML e normalmente editado em uma interface grática, que reflete a estrutura da base de dados.
Comment: https://stackoverflow.com/a/41599350/10991202

Duvida sobre a Classe Context


Special apostrophe breaks JSON

Question: <code>[7671] => Sleaford Carre's
</code>
is an element in $result
<code>$result=  json_encode($result);
echo $result;
//outputs
"7671":null,
</code>
Please note that this is not a normal apostrophe (single quote) or a back tick.
I cant even find it on my keyboard. Data comes from a Latin-1 table.
I have also noticed that using htmlentities on building the array will dissapear the string from the array. What am I to do??
Comment: have you tried to encode everything in UTF-8 first? This will solve many issues like this.
Comment: `json_encode()` expects UTF-8 encoded data.
Comment: I'd seriously look at transferring the data to a table that supports a modern encoding. Using 1990s legacy encodings is just asking for trouble.
Comment: Try to encode your string to UTF-8 first. Check this: http://php.net/manual/en/function.utf8-encode.php --- (utf8_encode function)
Comment: as the others have said, use utf8_encode() then json_encode().
Comment: using utf_encode() on building the array gives me `"7671":"Sleaford Carre\u0092s` That'll probably do it. thanks guys. Don't know how that data got entered!
Comment: Anyone want a green tick? I'll give you 10 mins. @quentin if I had a choice about legacy stuff, I wouldn't be using windows+sqlServer!
Answer: As no-one has actually written an answer, read the comments:)
as the others have said, use utf8_encode() then json_encode(). –  Brian

Special apostrophe breaks JSON


How can I correctly use Groupingby of JDK8 stream?

Question: public Map<Long, List<String>> groupby(){
 List<DTO> lst = getResultFromDB();
 Map<Long, List<DTO>> result =
                   lst.stream().collect(Collectors.groupingby(DTO:getId));
 return result;
}
class DTO {
 private Long id;
 private String code;
}

I want Map<Long, List<String>> (the String being DTO.getCode()), not Map<Long, List<DTO>>. How can I do it?
Comment: Sorry, I want Map> not Map>,the String equals  DTO.getCode().
Answer: You need to use Collectors.mapping to map code of DTO, in groupingBy
public Map<Long, List<String>> groupby() {
    List<DTO> lst = getResultFromDB();
    Map<Long, List<String>> result = lst
            .stream()
            .collect(Collectors.groupingBy(DTO::getId, Collectors.mapping(DTO::getCode, Collectors.toList())));
    return result;
}

Comment: Thanks a lot~ I get it.


Erro ao declarar constantes em Java

Question: Iniciei agora meus estudos em Java e estou com um problema ao declarar uma constante:
class Ex007
{
    public static void main(String[] args)
    {
        float comprimento, raio = 9f;
        public static final float PI = 1.1416f;
        comprimento = raio * PI * 2f;
        System.out.println("Comprimento: " + comprimento);
    }
}

O seguinte erro aparece:
ex007.java:6: error: illegal start of expression
        public static final float PI = 1.1416f;
        ^
ex007.java:7: error: <identifier> expected
        comprimento = raio * PI * 2f;
                   ^
ex007.java:8: error: <identifier> expected
        System.out.println("Comprimento: " + comprimento);
                          ^
ex007.java:8: error: illegal start of type
        System.out.println("Comprimento: " + comprimento);
                           ^
ex007.java:10: error: class, interface, or enum expected
}
^
5 errors

Se nesse código eu retirar o:
public static final

o PI se torna uma variável normal e o código funciona normalmente. Todos os tutoriais sobre constantes mostram que para declarar basta colocar o código:
public static final float NOME_CONSTANTE VALOR;

Mas isso não funciona aqui, tentei compilar no replt.it para ver se não era minha JDK e lá também não funcionou.
Answer: Na verdade é o seguinte, como voce esta no metodo main, voce nao pode definir atributos publicos, e por esta dentro de um metodo(main) voce nao pode definir atributos de classe(static). Ou seja, se voce tirar o public e o static vai funcionar.
Outra questao é nessa parte:
float comprimento, raio = 9f;
Voce esta tentando informar 2 variaveis em simultaneo: comprimento e raio, mas voce deve informar uma por vez.
Comment: Entendi, obrigado!

Erro ao declarar constantes em Java


Semiprimitive rings and Modules

Question: I'm finding for simple proofs of the followings facts:
$\bullet$ rad$(\Lambda/rad \Lambda)=0$
$\bullet$ rad$(A/rad \Lambda \ . A)=0$
$\bullet$ rad$(A/rad \Lambda \ . A)= rad A/ (rad\Lambda. A)$
where $\Lambda$ is a left Artin ring and $A$ is a $\Lambda$-module.
The first is a consequence of the $\Lambda/rad \Lambda$ is semisimple, but this is I want to conclude. The second is like the first if we consider $rad A=rad\Lambda \ . A$, but this I want to conclude too. So I want proof these facts without using the results I cited.
Answer: In the following I denote the Jacobson radical of an $R$ module $M$ as $J(M)$.
The fact that $J(R/J(R))=\{0\}$ is an elementary fact that holds for all rings.
Consider: the maximal right ideals of $R/J(R)$ are precisely of the form $I/J(R)$ where $I$ is a maximal right ideal of $R$.  The intersection of the maximal right ideals of $R/J(R)$ is, therefore, equal to $J(R)/J(R)=\{0\}$.
Now if you additionally have that $R$ is right Artinian, then $R/J(R)$ is right and left Artinian, indeed a semisimple ring owing to the fact we just proved. All modules over such a ring are also semisimple modules.
Of course, in a semisimple module $M$, $J(M)$ has to be equal to zero. For if it were not, then suppose $S$ is a simple submodule of $J(M)$: then $S\oplus N=M$ for some (obviously maximal) submodule $N$ of $M$. But $J(M)$ cannot be contained in $N$, a contradiction.
Now since $J(R)$ annihilates $\bar M=\frac{M}{MJ(R)}$, it is a $R/J(R)$ module, which is semisimple, hence $\bar M$ is semisimple, with zero Jacobson radical.
To me, the third item seems to be proven exactly as the first point, using correspondence of submodules.

Semiprimitive rings and Modules


Google play don't let me update my app

Question: I already made a huge search and don't know why Google Play are not letting me update my Prod app.
Their error message does not make too much sense for me, actually I don't understand for real why they are not accepting it.
This is the error message:
This configuration cannot be published for the following reason(s):
It is forbidden to downgrade devices which previously used M permissions (target SDK 23 and above) to APKs which use old style permissions (target SDK 22 and below). This occurs in the change from version 178 (target SDK 23) to version 2008 (target SDK 22).
It is forbidden to downgrade devices which previously used M permissions (target SDK 23 and above) to APKs which use old style permissions (target SDK 22 and below). This occurs in the change from version 178 (target SDK 23) to version 2008 (target SDK 22).
It is forbidden to downgrade devices which previously used M permissions (target SDK 23 and above) to APKs which use old style permissions (target SDK 22 and below). This occurs in the change from version 178 (target SDK 23) to version 2008 (target SDK 22).
It is forbidden to downgrade devices which previously used M permissions (target SDK 23 and above) to APKs which use old style permissions (target SDK 22 and below). This occurs in the change from version 178 (target SDK 23) to version 2008 (target SDK 22).

And here is a print of it:

The first build 0.1 was made using build.phonegap.com and the second one (0.2) was released locally using CLI because the results are better.
Anyone has some clue about that?
Thanks for reading.
Comment: can you post manifest file ?
Comment: I think you need to update your cordova to make sure that your app will support marhsmallow type permission checking. `cordova platform update email@example.com`
Answer: This is because your new build has a targetSdkVersion (22) lower than your current live build (23) in the manifest:
<uses-sdk android:targetSdkVersion="22" />
targetSdkVersion 23 is for Android 6+ where there is a new way to manage permissions : http://developer.android.com/training/permissions/requesting.html
So your current live users having Android 6+ are using the new permission system and it seems this is a problem for Google to downgrade those users to targetSdkVersion 22 where there is the old permission system.
So to fix it, you should update your new build to use targetSdkVersion 23 :
<uses-sdk android:targetSdkVersion="23" />
and so make sure you manage the new permission system.
Comment: The problem is not linked to the minSdkVersion, but to the targetSdkVersion. As you set target=23 in the previous build, all your Android 6 users currently runs your app with the new permission system. And this is what seems to be the problem for Google if you downgrade to target=22, because in that case, your Android 6 users would run your app with the old permission system.
Comment: That's weird because I've only set ``
Gonna try to set target 23 and min 15
Comment: Is there a way to do it without having to cater for android M permissions? Ie remove live version or something? I specifically made my update target lower due to permission issues.
Answer: For those using Xamarin, are getting this error and have not tried to downgrade their target SDK.
It appears Google Play displays this error if you change the supported ABIs. We recently published a build to Beta that was built using armeabi-v7a and x86. On our next build we removed x86 as it was unnecessary but we got the error above. So it appears that at the moment Google play does not support removing platforms you build for.
Answer: Late to the game but I have been seeing this a lot with Xamarin clients recently.
In addition to Andreas's excellent point, another possibility for those using Xamarin is that you might previously have set an explicit build target of 23 or higher but then reverted to Automatic.
Xamarin places < uses-sdk /> in the manifest when using Automatic which when replacing an APK that used an explicit target gives an error message as above but complaining of a change to target SDK 0. This happens even if the Automatic target is equal or higher than the existing SDK.
To solve this set an explicit target of 23 or higher
Answer: This has become a big problem for me too. I tested an apk that targets Api23, found out my app had problems when targeting 23, reverted to a lower Api and now I can't update my app without including the problems caused by 23.
Somebody here claims to have solved the problem by testing in Alpha, but that is not working for me: https://groups.google.com/d/msg/android-developers/dpK2XO025kQ/ciD_X4SoCQAJ
Edit: I talked to Google support and this is what they are suggesting now: With this issue, what you can do is press "disable beta testing" in the APK settings. This should resolve this issue for you. You should be able to go back to your previous API version.
I've had no luck so far, as my Beta Testing refuses to disable. So I'm working to properly adapt my app to Api 23.
This is clearly a bad move from Google. Put simply, with this policy you test a feature in Beta and the system forces you to implement it in Production, even if the testing went bad. Is that not bad practice?
Comment: I have the same issue...:(
Answer: Change Target Android Version
Automatic-use target framework --> Override - Android xx.
Comment: Where is that setting?

Google play don't let me update my app


Large $n,k$ asymptotics for Stirling numbrs of the first kind $\left[ \matrix{n\\k}\right]$

Question: $\left[ \matrix{n\\k}\right]$ is the notation for Stirling numbers of the first kind.  This is the number of distinguishable ways to break$n$ objects into $k$ cycles.  (Warning - Mathematica's StirlingS1 function is $(-1)^{n-k}$ times the usual definition of $\left[ \matrix{n\\k}\right]$.
I wanted to find an asymptotic expansion for $\left[ \matrix{n\\k}\right]$, good for general (large) $n$ and $k$.  This seems to be a lot too tough, so I will stick to my original motivating problem:

Find the large-$n$ asymptotic behavior of $\left[ \matrix{2n\\n}\right]$.

We can, by the recursion relation, immediately see that $\left[ \matrix{2n\\n}\right]$ grows at least as fast as $(n-1)!$, and in fact it is easier to work with the behavior of $$S(n) = \frac1{n!}\left[ \matrix{2n\\n}\right]$$
The term ratio
$$
R[n] \equiv \frac{ \left[ \matrix{2n+2\\n+1}\right] } {(n+1)  \left[ \matrix{2n\\n}\right]}
$$
seems to go to as
$$
R[n] \approx \exp\left( 2.2805 + \frac{0.0103}{\log n} - 0.0011 \log\left( \frac{\log 2}{\log n}\right) + O(1/n) \right)
$$
and since this was obtained by working with modest values of $n$ (around $500$) it is plausible that the last two coefficients are actually zero and the term ratio goes to a constant with order $1/n$ corrections.  Still, this does not get me to the desired asymptotic form for $\left[ \matrix{2n+2\\n+1}\right]$.
I appear to be stuck.
Answer: If you look at sequence $A187646$ in $OEIS$ (have a look here), you will find much more than a very good asymptotics proposed by Vaclav Kotesovec in 2011. It write
$$\color{blue}{\left[ \matrix{2n\\n}\right]\sim\frac 1 {\sqrt {2\pi}}\left(\frac{2n}{e(1-z) z}\right)^n \sqrt{\frac{1-z}{n (2 z-1)}}}$$ where $z=0.715331862959\cdots$ is the solution of equation
$$z=2 (z-1) \log (1-z)\implies \color{blue}{z=1+\frac{1}{2 W_{-1}\left(-\frac{1}{2 \sqrt{e}}\right)}}$$
Computing for a few values
$$\left(
\begin{array}{ccc}
n & \text{approximation} & \text{exact} \\
 10 & 3.88957\times 10^{14} & 3.81922\times 10^{14} \\
 20 & 1.09365\times 10^{36} & 1.08361\times 10^{36} \\
 30 & 6.64905\times 10^{59} & 6.60815\times 10^{59} \\
 40 & 1.28216\times 10^{85} & 1.27623\times 10^{85} \\
 50 & 3.19507\times 10^{111} & 3.18322\times 10^{111} \\
 60 & 6.08632\times 10^{138} & 6.06750\times 10^{138} \\
 70 & 6.27422\times 10^{166} & 6.25758\times 10^{166} \\
 80 & 2.74026\times 10^{195} & 2.73389\times 10^{195} \\
 90 & 4.22408\times 10^{224} & 4.21536\times 10^{224} \\
 100 & 1.99489\times 10^{254} & 1.99118\times 10^{254}
\end{array}
\right)$$
The relative error is $<1$% for $n>18$, $<0.1$% for $n>187$,  $<0.01$% for $n>1866$.
Based on the asymptotics,
$$R[n] = \frac{ \left[ \matrix{2n+2\\n+1}\right] } {(n+1)  \left[ \matrix{2n\\n}\right]}$$ for large values of $n$
$$\log(R[n])=\log \left(\frac{2}{(1-z) z}\right)-\frac{1}{n}+\frac{7}{12 n^2}+O\left(\frac{1}{n^3}\right)$$
which makes
$$\lim_{n\to \infty } \, R[n]=-\frac{8 \Big[W_{-1}\left(-\frac{1}{2 \sqrt{e}}\right)\Big]^2}{2 W_{-1}\left(-\frac{1}{2 \sqrt{e}}\right)+1}\approx 9.82163$$ while your approximation would lead to $e^{2.2805}=9.78157$.
Approximate and rigorous calculations of $R[n]$ give the following values
$$\left(
\begin{array}{ccc}
n & \text{approximation} & \text{exact} \\
 100 & 9.724466302 & 9.724645076 \\
 200 & 9.772786357 & 9.772831597 \\
 300 & 9.789008963 & 9.789029152 \\
 400 & 9.797142176 & 9.797153556 \\
 500 & 9.802029138 & 9.802036430 \\
 600 & 9.805290049 & 9.805295117 \\
 700 & 9.807620710 & 9.807624436 \\
 800 & 9.809369495 & 9.809372348 \\
 900 & 9.810730127 & 9.810732383 \\
 1000 & 9.811818928 & 9.811820755
\end{array}
\right)$$
Edit
Based on the exact values given in the above table and using quick and dirty nonlinear regression :

for your model
$$R[n]=\exp\left(a+\frac{b}{\log (n)}+c \log \left(\frac{\log (2)}{\log (n)}\right) \right)$$ ($SSQ=2.256\times 10^{-6}$) the results are
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 a & +2.522185 & 0.008303 & \{+2.501868,+2.542502\} \\
 b & -0.519993 & 0.015108 & \{-0.556962,-0.483025\} \\
 c & +0.071063 & 0.002672 & \{+0.064524,+0.077601\} \\
\end{array}$$
for the model
$$R[n]=\exp\left(a+\frac{b}{n}+\frac{c}{n^2} \right)$$ ($SSQ=3.705\times 10^{-14}$) the results are
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 a & +2.284587 & 7.28 \times 10^{-9} & \{+2.284587,+2.284587\} \\
 b & -0.999960 & 4.29 \times 10^{-6}  & \{-0.999971,-0.999950\} \\
 c & +0.759431 & 3.89 \times 10^{-4} & \{+0.758478,+0.760383\} \\
\end{array}$$
Comment: @Mark Fischler. Interesting is to notice that $\log \left(\frac{2}{(1-z) z}\right)=2.2846$ to be compared to your $2.2805$.
Answer: The exponential generating function for the signed Stirling numbers of the first kind $s(n, k)$ is $\ln^k(x + 1)/k!$, so we have
$$s(n, k) = \frac {n!} {k!} [z^n] \ln^k(z + 1) =
\frac {n!} {2 \pi i k!} \int_{|z| = \epsilon}
 \frac {\ln^k(z + 1)} {z^{n + 1}} dz.$$
We want to apply the steepest descent method to $e^{n \phi(z)}/z$ with $\phi(z) = -2 \ln z + \ln \ln(z + 1)$. The stationary point of $\phi$ is at
$$\alpha = -\frac 1 {2 W_{-1} {\left( -\frac 1 {2 \sqrt e} \right)}} - 1,$$
so we need to take a branch of $\phi$ which is analytic at $\alpha$. Since $(2 n)!/n! \sim \sqrt 2 \, (4 n/e)^n$, we get the asymptotic estimate
$$(-1)^n s(2 n, n) \sim
-\frac {\sqrt 2} {2 \pi i \alpha}
 \sqrt {-\frac {2 \pi} {\phi''(\alpha) n}}
 \left( -4 n e^{\phi(\alpha) - 1} \right)^{\! n},
\quad n \to \infty.$$
The negative square root corresponds to going through the saddle point in the direction $-i$. The result is the same as in Claude's answer.
Comment: NIce approach of the problem. Louchard worked in this direction http://algo.inria.fr/pf60/program_files/Louchard.pdf


Finding the long and short axes of an ellipses after applying an anisotropic scaling

Question: Suppose I have an ellipse with long axis $l_1$, short axis $s_1$ and say it has an orientation of $\frac{\pi}{2}$ (unnecessary but the graphic I remembered after I created the graphic attached that the usual convention is to have the long axis aligned to the x-axis).

Now suppose I apply an anisotropic scaling (scaling along two orthogonal axes); specifcally I scale by some factor $k_1$ in the direction of some vector $\vec{v}_1$ and by some other factor $k_2$ in the direction of a vector $\vec{v}_2$ that is orthogonal to $\vec{v}_1$. For non-trivial values such scaling maps an ellipse to an ellipse.
Given the directions of $\vec{v}_1$ and $\vec{v}_2$, the scaling factors $k_1$ and $k_2$ and the original ellipse parameters $l_1,s_1$ and $\theta_1$ (for completeness - its orientation relative to the x-axis / angle between long axis and x-axis), what are the new long and short axes -  $l_1'$ and $s_1'$ respectively?

Initial attempt:
Assuming it to be centered at the origin, I applied the transformations to the ellipse parameterization and then sought out to transform that parameterization to some form $(l_1' \cos(t)\cos(\theta_1') - s_1' \sin(t)\cos(\theta_1'),l_1' \cos(t)\sin(\theta_1') + s_1' \sin(t)\sin(\theta_1'))$ where $\theta_1'$ is the angle $l_1'$ makes with the x-axis.
This turns out to be nearly impossible or at least way above what I'm seeking, since there are so many variables involved.
I also thought of finding the max of the ellipse parameterization after applying the transformations, however also not exactly straight forward since it depends on the scaling factors and directions - but could be numerically achievable I suppose when one provides specific scaling factors and directions. However, I'm not seeking a numerical solution.
So is there a straightforward analytic way to find the long and short axis of the transformed ellipse?
Thanks in advance!
Comment: Related: https://math.stackexchange.com/q/596016/97045
Answer: The equation of the starting ellipse (assuming it is centered at the origin) can be written as
$ r^T Q r  = 1 $
where $ r =[x, y]^T $
If the semi-axes are $a$ and $b$ with $a \gt b$, and assuming the orientation of the major axis is parallel to the y-axis then
$Q = \begin{bmatrix} \dfrac{1}{b^2} && 0 \\ 0 && \dfrac{1}{a^2} \end{bmatrix} $
Now you want to apply scaling to the points $r$
along a certain given pair of orthogonal unit vectors $v_1$ and $v_2$ such that the component of $r$ along
$v_1$ get stretched by $k_1$ and the component of $r$ along $v_2$ gets stretched by $k_2$
The components of $r$ onto $v_1$ and $v_2$ are easily computed by defining
$R = [v_1, v_2] $
Then the components (the coordinates) of $r$ with respect to $v_1 $ and $v_2$ are given by
$r_1 = R^T r $
Next we want to stretch the two entries of $r_1$ by $k_1$ and $k_2$ respectively, so define the diagonal matrix $D$, as follows
$D = \begin{bmatrix} k_1 && 0 \\ 0 && k_2 \end{bmatrix}$
then it would follow that the stretched coordinates are given by $r_2$ where:
$ r_2 = D r_1 = D R^T r $
The image of $r$ is not $r_2$ but $ R r_2 $
i.e.
$r' = R D R^T r  = A r $
Having found the image $r'$ of a point $r$ on the ellipse, we can write the equation of the new ellipse.
We have $ r = A^{-1} r' = R D^{-1} R^T r' $
substitute this into the equation of the original ellipse, to obtain,
$ r'^T R D^{-1} R^T Q R D^{-1} R^T r' = 1 $
Define $Q' = R D^{-1} R^T Q R D^{-1} R^T$
then the equation of the new ellipse is
$ r'^T Q' r' = 1 $
To obtain the semi-major and semi-minor axes lengths, we have to perform diagonalization of $Q'$ into
$Q' = R' D' R'^T $
Then the diagonal matrix $D'$ is of the form
$D' = \begin{bmatrix} \dfrac{1}{a'^2} && 0 \\ 0 && \dfrac{1}{b'^2} \end{bmatrix} $
Now $a'$ and $b'$ are the sought lengths of the semi-major and semi-minor axes.  The directions of these axis are stored respectively in the matrix $R'$
Answer: I can suggest two different strategies.

Choose at will five points on the original ellipse and apply to them the anisotropic scaling. The transformed points define a conic which is then the transformed of the ellipse. From them you can get the equation of the new ellipse and then its axes.

From the center of the original ellipse trace a line parallel to $\vec v_1$, intersecting the ellipse at diameter $AB$. Construct then the conjugate diameter $CD$ (i.e. tangents at $C$ and $D$ are parallel to $\vec v_1$).
The transformed segments $A'B'$ and $C'D'$ are conjugate diameters of the transformed ellipse, and you can then find its axes as explained here.


Editing a referenced class

Question: I'm working with a Maven project. In a referenced JAR there is a package, which contains a class file. I need to add some lines of code to this class, but unfortunately this class it not editable.
My idea was to create a new class, extend it from this referenced class and add my lines of code to the newly created class. The problem here is, the code is a bit complex and the classes extend from one another.
// existing class
public class ReferencedClass extends AnotherClass{
  // ...
}
// my idea
public class MyClass extends ReferencedClass{
  // add my code here
}

// where those classes are needed
public class SomeClass{
  anObject o = new anObject(); // creates new object, whose class also extends from ReferencedClass
}
// this class also extends from ReferencedClass
public class anObject extends ReferencedClass{
  // ...
}

I'm not sure, how to instantiate my own created class MyClass. Should I do it in all classes, where ReferencedClass is also used?
Is there another solution to my problem, without creating a new class at all?
Thank you!
Comment: If I were you, I'd make a wrapper class, and use only that class in your own project/code.
Comment: It's difficult to provide meaningful advice, but if the class you want to modify isn't yours, you probably shouldn't modify it. Whether or not you should extend the same class is difficult to say without knowing what you really want to do with it. Alternatives include things like AOP, simple composition with delegation, decorators, etc.
Comment: @DaveNewton: I only need to add a short setter-method.
Comment: @stealthjong: You mean a wrapper around the referenced class? Could you provide me with a short example please?
Answer: If you want to modify a field without a setter, a wrapper isn't useful. Whether or not the next solution is useful, is dependant on whether or not the field you are trying to modify is private or protected. If the access modifier is private, only instances of the class itself can modify the field. If protected, a child class can also access and modify the field.
//this is our class within the library. We cant edit its source
class APIClass {
    private int privatefield;
    protected int protectedfield;

    public String doStuff() { ... }
    public int doMoreStuff() { ... }
}

class MyExtendedAPIClass extends APIClass {
    // you dont have to override doStuff and doMoreStuff

    void setValues() {
        protectedfield = 10; //compiles, protectedfield is protected
        privatefield = 1; //does not compile, privatefield is private
    }
}

If it's a private field, and you still want to change its value, you can use reflection (in that case, you don't need another class):
void setFieldWithReflection() {
    APIClass apiClass = new APIClass();
    try {
        Field fieldToEdit = apiClass.getClass().getField("privatefield");
        fieldToEdit.set(apiClass, 25);
    }
    catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

Edit: Since a setter merely sets a field, you can just set that field using reflection. But OP demands it to be a method (which I don't get, but OK), I'd go with this implementation:
//this is our class within the library. We cant edit its source
class APIClass {
    private int privatefield;

    public int getPrivatefield() {
        return privatefield;
    }
}

class MyExtendedAPIClass extends APIClass {
    // you dont have to override doStuff and doMoreStuff

    public void setPrivatefield(int value) {
        try {
            Field field = this.getClass().getSuperclass().getDeclaredField("privatefield");
            field.setAccessible(true);
            field.set(this, value);
        }
        catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Above works. Test with code
MyExtendedAPIClass mApi = new MyExtendedAPIClass();
mApi.setPrivatefield(5);
System.out.println(mApi.getPrivatefield);//outputs '5'

Comment: Thank you! I just need to add another setter method to the class, without modifying any fields.

Editing a referenced class


Analysis of 90% threads in java.lang.Thread.State: WAITING (parking)

Question: Thread count in my tomcat application server is growing every day.
When I have taken thread dump for analysis.
I found that out of 430 threads 307 threads are with this status.
Sample stacktrace
"pool-283-thread-1" #2308674 prio=5 os_prio=0 tid=0x000000000a916800 nid=0x1101 waiting on condition [0x00002aec87f17000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000006d9929ec0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
    - None

"pool-282-thread-1" #2307106 prio=5 os_prio=0 tid=0x000000000a4fb000 nid=0x78e3 waiting on condition [0x00002aec87e16000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x00000006d8ca7bf8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
    - None

Environment
JDK: jdk1.8.0_60
OS: Linux
Tomcat: tomcat-7.0.65

Not sure if this is causing the issue.
Appreciate any help on this.
Comment: Those threads appear to be a thread pool waiting for a task in a queue.  I think you'll have to tell us how you setup that thread pool and queue.
Comment: Do you happen to miss a shutdown on a threadpool/ExecutorService?
Answer: This is typical resource leak. You are using some sort of ExecutorService somewhere in your application and you are not closing that pool after work is done causing threads to await forever.
You should call ExecutorService#shutdown() to close pool and release/terminate its threads after work is done.
Threads names like pool-282-thread-1 pool-283-thread-1 suggests that you are most probably using single thread pool executor (because pool no. is large and thread no. is only 1). The idea behind ExecutorService is to reuse threads that are idle to do some more work. So insteed of createing new ExecutorService each time you need to do some background work, you should rather share single instance and use it in your application.
Answer: This issue happened in our application. We fixed it by using single ExecutorService instead of creating ExecutorService each time.
Comment: Hi Krishnan, welcome to SO.  Please be sure to read the rules while you're here.  Answers should be left to answers to the question, not +1 or thanks posts.  If you could add some code to show your solution it would help this post a lot.  Cheers!