Poor upload/download speed on 2 x ADSL lines into a Cisco 2621XM

Question: Sorry never been on this site before so I apologise if not the right section or even forum.
I have users complaining of very slow internetn connectivity on site and have checked with our ISP who have said that the line is testing at 8mb.
We have 2 x BT lines that have our ISP broadand on them. Both lines go into a Cisco 2600 series router that then has a PIX firewall off that. Connectivity is successful just gone really slow and unable to download anything.
Config is below:
version 12.3
no service pad
service tcp-keepalives-in
service tcp-keepalives-out
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
!
hostname ROUTER-ADSL-INTERNET
!
logging buffered 16384 informational
enable secret xxx
enable password xxx
!
username xxx
username xxx
clock summer-time UK recurring last Sun Mar 1:00 last Sun Oct 1:00
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local
aaa session-id common
ip subnet-zero
no ip source-route
!
!
!
ip audit notify log
ip audit po max-events 100
no ip bootp server
ip name-server 18.104.22.168
no mpls ldp logging neighbor-changes
no ftp-server write-enable
!
!
!
!
!
!
!
!
!
!
no voice hpi capture buffer
no voice hpi capture destination
!
!
!
!
!
!
!
!
interface ATM0/0
 description 01270 111111
 no ip address
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 1
 !
 dsl operating-mode auto
!
interface FastEthernet0/0
 ip address 126.96.36.199 255.255.255.248
 shutdown
 speed 100
 full-duplex
 no cdp enable
!
interface ATM0/1
 description 01270 222222
 no ip address
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 1
 !
 dsl operating-mode auto
!
interface FastEthernet0/1
 ip address 18.104.22.168 255.255.255.240
 duplex auto
 speed auto
 no cdp enable
!
interface Dialer0
 ip address 126.96.36.199 255.255.255.248
 encapsulation ppp
 dialer pool 1
 dialer-group 1
 ppp authentication chap callin
 ppp chap hostname email@example.com
 ppp chap password 7 xxxxx
 ppp multilink
!
ip classless
ip route 0.0.0.0 0.0.0.0 Dialer0
!
no ip http server
no ip http secure-server
!
no logging trap
access-list 10 permit 18.104.22.168
access-list 10 permit 22.214.171.124
access-list 10 deny   any
access-list 22 permit 18.104.22.168
access-list 22 permit 22.214.171.124
access-list 22 permit 18.104.22.168
access-list 22 deny   any
dialer-list 1 protocol ip permit
no cdp run
!
!
snmp-server community xxxxxx RO 10
snmp-server enable traps tty
radius-server authorization permit missing Service-Type
!
!
!
!
!
!
line con 0
 exec-timeout 5 0
 password 7 xxxxxx
line aux 0
 no exec
line vty 0 4
 access-class 22 in
 exec-timeout 5 0
 password 7 xxxxxx
 transport input telnet ssh
 transport output none
line vty 5 15
 password 7 xxxxxx
 transport input telnet ssh
!
ntp clock-period 17180095
ntp server 188.8.131.52
!
!
end

Now my knowledge is very limited but ISP have said that while the lines are bonded each needs a seperate login as they've recently changed their L2TP router and that enforces the use of seperate logins - when the lines were configured we were given two logins.
So, my question is what changes do I need to make to the config in order to get this working? it was ok before their change and I do have another login :-

01270 111111 - firstname.lastname@example.com
  01270 222222 - email@example.com

Does the IP address for dialer1 need to be the same as dialer0 as its just the authentication that is the problem?
Do I need to make a change to ip route 0.0.0.0 0.0.0.0 Dialer0 as I've created another dialer interface?
current config below:
version 12.3
no service pad
service tcp-keepalives-in
service tcp-keepalives-out
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
!
hostname XT-ADSL-INTERNET
!
logging buffered 16384 informational
no logging console
enable secret 5 x
enable password 7x
!
username x
clock summer-time UK recurring last Sun Mar 1:00 last Sun Oct 1:00
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local
aaa session-id common
ip subnet-zero
no ip source-route
!
!
!
ip audit notify log
ip audit po max-events 100
no ip bootp server
ip name-server 18.104.22.168
no mpls ldp logging neighbor-changes
no ftp-server write-enable
!
!
!
!
!
!
!
!
!
!
no voice hpi capture buffer
no voice hpi capture destination
!
!
!
!
!
!
!
!
interface ATM0/0
 description 01270 111111
 no ip address
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 1
 !
 dsl operating-mode auto
!
 interface FastEthernet0/0
shutdown
 speed 100
 full-duplex
 no cdp enable
!
interface ATM0/1
 description 01270 222222
 no ip address
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 2
 !
 dsl operating-mode auto
!
interface FastEthernet0/1
 ip address 184.108.40.206 255.255.255.240
 duplex auto
 speed auto
 no cdp enable
!
 interface Dialer0
 ip address 22.214.171.124 255.255.255.248
 encapsulation ppp
 dialer pool 1
 dialer-group 1
 ppp authentication chap callin
 ppp chap hostname firstname.lastname@example.com
 ppp chap password xxxx
 ppp multilink
!
interface Dialer1
 ip address 18.104.22.168 255.255.255.248
 encapsulation ppp
 dialer pool 2
 dialer-group 2
 ppp authentication chap callin
 ppp chap hostname firstname.lastname@example.com
 ppp chap password xxxx
 ppp multilink
!
ip classless
ip route 0.0.0.0 0.0.0.0 Dialer0
!
no ip http server
no ip http secure-server
!
no logging trap
access-list 10 permit 126.96.36.199
access-list 10 permit 184.108.40.206
access-list 10 deny   any
access-list 22 permit 220.127.116.11
access-list 22 permit 126.96.36.199
access-list 22 permit 18.104.22.168
access-list 22 deny   any
dialer-list 1 protocol ip permit
no cdp run
!
!
snmp-server community caudwell-xt RO 10
snmp-server enable traps tty
radius-server authorization permit missing Service-Type
!
!
!
!
!
!
line con 0
 exec-timeout 5 0
 password 7 xxx
line aux 0
 no exec
line vty 0 4
 access-class 22 in
 exec-timeout 5 0
 password 7 xxx
 transport input telnet ssh
 transport output none
line vty 5 15
 password 7 xxx
 transport input telnet ssh
!
ntp clock-period 17180095
ntp server 220.127.116.11
!
!
end

Apologies for the long question and thanks for taking the time to read it. Any more info I can provide please let me know.
Comment: I think your bandwidth is probably rated in Mb, not mb,
Comment: wow, it's amazing how much security info you left in your config, I now know your phone number, your access list policies, your dialup username. Why are you using adsl? cant you get a fibre link, rather than a technology which is a horrible hack.
Answer: I think what you need to add is another dailer interface like this:
interface Dialer1
 ip address x.x.x.x 255.255.255.248
 encapsulation ppp
 dialer pool 2
 dialer-group 2
 ppp authentication chap callin
 ppp chap hostname email@example.com
 ppp chap password 7 xxxxx
 ppp multilink
!

then you use the new dailer pool for the second ATM interface.
interface ATM0/1
 description 01270 222222
 no ip address
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 2
 !
 dsl operating-mode auto
!

Modify and fill in as needed. You might want to have a look at the cisco ios documentation: http://www.cisco.com/en/US/docs/ios/12_0/dial/configuration/guide/dcdbakdp.html#wp3753
Comment: sorry me again, i'll have to try this after 5pm as any changes may affect current users. Just wanted to confirm something Does each dialer interface have to have a seperate login? your answer uses the same login as existing setup but thought I needed a seperate one? I've been given: 01270 111111
u/n firstname.lastname@example.com (currently being used on Dialer0)
p/w password 01270 222222
u/n email@example.com
p/w password Thanks Again In Advance,
Comment: The dialer interface specifies the settings used for the connection, including login/password, so you would have to modify what I wrote to include the correct phone number and such, yes.
Answer: interface ATM0/0
 description 01270 111111
 no ip address
 logging event subif-link-status
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 1
 !
 dsl operating-mode auto
!
!
interface ATM0/1
 description 01270 222222
 no ip address
 logging event subif-link-status
 no atm ilmi-keepalive
 pvc 0/38
  encapsulation aal5mux ppp dialer
  dialer pool-member 2
 !
 dsl operating-mode auto
!

interface FastEthernet0/1
 ip address 126.96.36.199 255.255.255.240
 duplex auto
 speed auto
 no cdp enable
!

interface Dialer0
 ip address negotiated
 ip nat outside
 ip load-sharing per-packet
 encapsulation ppp
 dialer pool 1
 dialer idle-timeout 0
 dialer persistent
 ppp authentication chap callin
 ppp chap hostname firstname.lastname@example.com
 ppp chap password 7 xxxxxxxx
!

interface Dialer1
 ip address negotiated
 ip nat outside
 ip load-sharing per-packet
 encapsulation ppp
 dialer pool 2
 dialer idle-timeout 0
 dialer persistent
 no cdp enable
 ppp authentication chap callin
 ppp chap hostname email@example.com
 ppp chap password 7 xxxxxxxx
!
ip classless
no ip route 0.0.0.0 0.0.0.0 Dialer0
ip route 0.0.0.0 0.0.0.0 188.8.131.52
ip route 0.0.0.0 0.0.0.0 Dialer1 200


How to get form data from POST request in Java

Question: How to I extract form data from a POST request eg. $ curl -X POST -d asdf=blah http://localhost:8000/proxy/http://httpbin.org/post - and I need to extract asdf=blah.
The way I am currently doing it relies heavily on the data I have read being in a certain format (I am assuming the form data is always on the last line). Is there a better (and/or simpler)  way to get the data which does not depend on the format of the data being read ?
(Note: the proxy deals with both GET and POST requests)
Here is code I have written :
<code>public class ProxyThread3 extends Thread {
private Socket clientSocket = null;

private OutputStream clientOutputStream;

private static final int BUFFER_SIZE = 32768;

public ProxyThread3(Socket socket) {
    super("ProxyThread");
    this.clientSocket = socket;

}

public void run() {
    try {

        clientOutputStream = clientSocket.getOutputStream();

        // Read request
        InputStream clientInputStream = clientSocket.getInputStream();

        byte[] b = new byte[8196];
        int len = clientInputStream.read(b);

        String urlToCall = "";

        if (len > 0) {

            String userData = new String(b, 0, len);

            String[] userDataArray = userData.split("\n");

            //Parse first line to get URL
            String firstLine = userDataArray[0];
            for (int i = 0; i < firstLine.length(); i++) {

                if (firstLine.substring(i).startsWith("http://")) {

                    urlToCall = firstLine.substring(i).split(" ")[0];
                    break;
                }

            }

            //get request type
            String requestType = firstLine.split(" ")[0];

            String userAgentHeader = "";

            //get USER-AGENT Header and Accept Header
            for (String data : userDataArray) {

                if (data.startsWith("User-Agent")) {

                    userAgentHeader = data.split(":")[1].trim();
                    break;

                }

            }

            switch (requestType) {

                case "GET": {

                    sendGetRequest(urlToCall, userAgentHeader);
                    break;
                }

                case "POST": {

                    String postParams = null;

                    //Get Form Data
                    if (!userDataArray[userDataArray.length - 1].isEmpty()) {

                        postParams = userDataArray[userDataArray.length - 1];

                    }

                    sendPostRequest(urlToCall, userAgentHeader, postParams);
                    break;
                }

            }

        } else {
            clientInputStream.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void sendPostRequest(String urlToCall, String userAgentHeader,  String postParams) throws IOException {

    URL urlToWriteAndReadFrom = new URL(urlToCall);

    HttpURLConnection httpURLConnection = (HttpURLConnection) urlToWriteAndReadFrom.openConnection();

    httpURLConnection.setRequestMethod("POST");

    // set User-Agent header
    httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);

    httpURLConnection.setDoOutput(true);

    OutputStream urlOutputStream = httpURLConnection.getOutputStream();

    if (postParams != null) {
        urlOutputStream.write(postParams.getBytes());
        urlOutputStream.flush();

    }

    urlOutputStream.close();

    int responseCode = httpURLConnection.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) { // success

        InputStream dataReader = httpURLConnection.getInputStream();

        //begin send response to client
        byte inputInBytes[] = new byte[BUFFER_SIZE];

        assert dataReader != null;

        int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);

        while (index != -1) {
            clientOutputStream.write(inputInBytes, 0, index);
            index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
        }
        clientOutputStream.flush();

    }

}

private void sendGetRequest(String urlToCall, String userAgentHeader) throws IOException {

    URL urlToReadFrom = new URL(urlToCall);
    HttpURLConnection httpURLConnection = (HttpURLConnection) urlToReadFrom.openConnection();

    // set True since reading and getting input
    httpURLConnection.setDoInput(true);
    httpURLConnection.setRequestMethod("GET");

    // set User-Agent header
    httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);

    int responseCode = httpURLConnection.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) { // success

        InputStream dataReader = httpURLConnection.getInputStream();

        //begin send response to client
        byte inputInBytes[] = new byte[BUFFER_SIZE];

        assert dataReader != null;

        int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);

        while (index != -1) {
            clientOutputStream.write(inputInBytes, 0, index);
            index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
        }
        clientOutputStream.flush();

    }

}
</code>
}
PS. I am new to all of this so if there are any errors in my code, please do point them out
Answer: Here is a full example on how to create a Java HTTP server that handles POST and GET requests.

https://www.codeproject.com/Tips/1040097/Create-a-Simple-Web-Server-in-Java-HTTP-Server

That being shared, this is quite primitive, I'd recommend using any third party library or light-weight Java server like Grizzly or Jetty if not a server like Apache Tomcat utilizing J2EE Servlets which are made for this purpose.
Comment: Thanks ! Although the example was not completely what I was doing, it helped me a lot with getting the form data from the POST request


How to make my old JFrame to JPanel, and how to make it actually work as it worked while I used JFrame

Question: Im really new to swing lib, like maybe 5 days ago I started using it... so I have so many problems... first, I made a Tic Tac Toe game on a JFrame, it would be cool to leave it like that, but then I came with the idea to make a small menu to acces multiple little games (just for fun/practice so far). So I actually succed, then it happens... I made all my games in JFrames so, to make a menu its also another JFrame, so I have so many windows... all the time!
I made some research and people usually makes Jpanels for this kind of stuff.. But I dont know how to transfer my games (Tic Tac Toe) to a JPanel and make it work exactly as it was... here is my code of the Tic Tac Toe in JFrame... the IDE is netbeans.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;

public class Gato extends javax.swing.JFrame implements ActionListener {

Boton MAPA[][];

public static boolean turno=true;

 public Gato(){
    initComponents();

    MAPA= new Boton[3][3];

     for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
             MAPA [i][j]=new Boton();
             MAPA[i][j].u.setBounds((i*230)+10,(j*230)+10,230,230);
             MAPA[i][j].u.addActionListener(this);
             this.add(MAPA[i][j].u);
         }

     }
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     JLabel o=new JLabel("Hola");
     o.setBounds(60, 60, 100, 100);
     this.add(o);

}

Comment: For many components in one space (e.g. both game and menu), use a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) (in the frame) as seen in this [short example](http://stackoverflow.com/a/5786005/418556).
Comment: `o.setBounds(60, 60, 100, 100);` Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs.  As such they are not conducive to exact placement of components.  To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556).
Answer: How you should structure your JPanels inside a JFrame is an an architectural question that is beyond the scope of this site.
To help wrap your head around what the difference between these two sorts of containers:
Change public class Gato extends javax.swing.JFrame implements ActionListener {
to public class Gato extends javax.swing.JPanel implements ActionListener {
Then, create a new "driver" class that does something like this:
   public static void main(String[] args){
         JFrame frame = new JFrame();
          Gato gato = new Gato();
          frame.setContentPane(gato);
          frame.setVisible(true);
    }

The only difference between a JFrame and a JPanel is that a JFrame is a top-level container - it exists as its own window - while a JPanel is something that has to be loaded inside a top-level container. Here is a great discussion about the difference between them conceptually.
In practice, once you have your frame created and your panel embedded into it (there are some quirks to this process, and I'll admit they tripped me up quite a few times when I was first wrapping my head around Swing - be sure to read the documentation very carefully, paying particular attention to JFrame.pack() and JPanel.validate()), you can treat that panel exactly as you would if it was a frame.
In fact, I often test JPanel elements by changing them to JFrames in order to test them independent of any container.
Answer: Instead of adding components to the JFrame, add them to a JPanel, then add the JPanel to the JFrame.
Comment: tried that... but it wont show the JPanel on the JFrame idk why
Comment: @AlbertoCantu Then post the code where you do this so we can see what the problem really is. Understand that when you add components to a `JFrame` it really adds them to its content pane which behaves like a `JPanel`.
Answer: Well for your problem you just need one JDesktopPane and All your JFrame need JIternalFrame and call all InternalFrame in JDesktopPane.
Go to this link and check out examples
you don't need to convert them into panel and all.
or you can also try netbeans inbuilt examples for JDesktopPane.
Comment: Why would he need many frames? This is only confusing to the user and serves no purpose in game menus if your menu is floating in one place and the game somewhere else.


Why use 5 or more ledger lines below the bass clef instead of ottava bassa lines for piano sheet music?

Question: One thing that has bothered me when listening to classical music with the sheet music also scrolling by is its persistent use of 5 or more ledger lines for low enough bass clef parts instead of ottava bassa lines.
Examples (all pulled from public domain scores on IMSLP):
Camille Saint-Saëns's Prélude et fugue, F minor, Op. 52, No. 3 - published by Paris: Durand, n.d. Plate D. & F. 2339. Reissue (new engraving) - ca.1900

Sergei Rachmaninoff's Prelude in C Sharp Minor, Op. 3, No. 2

Frédéric Chopin's Prelude in C Minor, Op. 28, No. 20

I find this use of 5 or more ledger lines below the bass clef to both be less readable than ottava bassa lines and against the tendency for notes above the treble clef to use ottava alta lines instead of 5 or more ledger lines. (At least, I've found notes above the treble clef to much more commonly be found with ottava alta lines instead of 5 or more ledger lines.)
Examples of ottava alta lines for notes above the treble clef instead of 5 or more ledger lines...or even fewer ledger lines than 5 (again, all pulled from public domain scores on IMSLP):
Camille Saint-Saëns's Prélude et fugue, F minor, Op. 52, No. 3 - from the exact same score as the other excerpt from that piece:

Franz Liszt's Tarantelle di bravura d'après la tarantelle de La muette de Portici, S.386

Franz Liszt's Grand galop chromatique, S.219

Why does this double standard regarding the use of ottava lines vs. ledger lines exist? Why are notes with 5 or more ledger lines so much more common below the bass clef than above the treble clef? Why don't publishers pick exactly one, more readable standard and stick to it?
Comment: In each of the cases cited, the left hand is in octaves. This is generally easy to see. On the other hand, the right hand parts are much more complex and varied, so having the staff available is especially helpful.
Comment: There seems to be an assumption in the question that using ottava makes things "more readable".  And it may be true for the OP but perhaps not for everybody.  The examples cited don't seem that hard to read to me, although if they were not actually octaves then it might be harder I suppose.
Comment: @Aaron that sounds like an answer.
Comment: @Aaron - I've honestly found those octaves with 5 or more ledger lines to be less readable than just using ottava lines. Counting out the ledger lines and deducing notes from there has been a slight pain.
Comment: When I see something like that, I try to figure out if the interval between the higher note and the low one is constant and, if so, I just ignore the low note reading because I know it's there. But, without the top note, for me it would be significantly harder to read.
Comment: I recognize the basis for your question. Leaving aside the "why", there are two things that help me with these bass passages: 1) recognizing the visual "size" of an octave and 2) once I see a series of octaves, reading the upper note and/or reading by melodic intervals. I had similar problems as you describe, and these two elements all but eliminated the issues.
Comment: @phoog The minute I can back it up with some evidence....
Comment: Gestalt perception. In your first example, looking at the shape of the score tells me immediately that the two C octaves are an octave apart. If the lower one were notated with ottava lines, it would become a nightmare of calculating and second-guessing.
Comment: I agree that these low notes are easy to read because they include the note an octave above which is easy to read.  String players are used to reading 5 or more leger lines above the stave, and tuba players the same below the stave.  You just get used to reading them with time and exposure.
Comment: @KilianFoth - I've played the first score multiple times before, and each time, discovering that those lowest notes are an octave apart has **not** been immediate. Even reading it now, I much prefer ottava lines - **now** reading that notes are an octave apart is immediate.
Comment: Related: https://music.stackexchange.com/questions/111854/is-there-any-official-semi-official-standard-for-music-symbol-visual-appearance
Answer: Let's look at your first example, the Saint-Saëns.
Yes, if there was ONLY the lowest C, it would be difficult to read and an 8vab line would help.   But the higher C, on just two ledger lines, is easy to read, as is the octave interval. So we can allow the music to retain the correct 'shape' with low notes LOOKING low - this also is an important factor in readability.
The same principle applies to all your other examples.  There's an 'easy' (few or no ledger lines) to give us our bearings coupled with an easily detected octave interval.
A, below, is arguably better written as B.   But C is easy to read, easier than D because it shows where the notes are physically.
Comment: the logic of choosing between these four options is explained and illustrated very clearly
Comment: What the? I still find D easier to read than C.
Comment: +1 for pointing out that there are multiple factors at work. An ottava line is good for avoiding very remote note heads if there is nothing to relate them to. But interrupting a longer line that *contains* individual remote notes is usually counterproductive.
Comment: What I find lacking in these examples is they are isolated measures. The question of whether to use an octave mark or not is largely context dependent. If the surrounding measures are also very low, then marking a whole phrase an octave down is easy to read. If the surrounding measures are linked in a phrase with the lowest notes and descent downwards or ascend upwards from the lowest notes, then an octave mark may make it harder to read. So it is with the examples in the question - the context is important.
Comment: I wonder if it would have been useful to have a convention that the third through seventh ledger lines be shown wider than the first two?  The wider ledger lines would then correspond to the lines of the staff to which they are attached, but separated by two octaves.
Comment: @Dekkadeci I think your comment here explains a lot: It seems like many pianists and publishers have an easier time reading C versus D (including myself), and so that explains why you are seeing publishers notate more like C than D. The fact that you prefer D unfortunately makes you an unusual case. You could either learn to read notation like C more easily or you could make transcriptions of works that you are playing to make them easier to read. Either way, the answer to "why C instead of D?" is that many others prefer it.
Comment: @ToddWilcox - With the context of Excerpt 2, I can definitely see using ottava lines on the LH C# octaves only, and for Excerpt 3, on all LH octaves that involves the G below the C 2 octaves below Middle C or lower.
Comment: @ToddWilcox - Additionally, why would those same readers prefer C over D and then not complain about how badly and/or inconsistently notated Excerpt 5 is? If they can easily read 5 ledger lines below the bass clef, surely they can easily read 4 ledger lines above the treble clef.
Comment: @Dekkadeci D may be easier to read than C in isolation, but when you have C1/C2 following C3/C4, the use of _8va bassa_ on only the lower notes obscures the two-octave distance.  Using it on the entire bass staff results in excessively many ledger lines on the C4, which would have to be notated as C5.
Answer: First, musicians should learn to read lots of ledger lines. If you are frustrated by them, that's an important thing to focus on for your studies until you can read them easily.
Second, it is harder to read music fluidly when the 8va or 8vb marks are very brief - a full measure is a good minimum to keep in mind (with some exceptions). You can't see the flow of the music when the octave is frequently changing. In your third to last example, Camille Saint-Saëns's Prélude et fugue, F minor, Op. 52, No. 3, the 8va is poorly used, and I strongly suspect that was a decision made by the publisher to save space. The last two examples show entire passages played an octave higher than the treble clef. This is appropriate use of an octave sign.
Your first three examples would have to have overly brief 8vb marks that would hinder reading, not help it.
Finally, as Laurence Payne points out, in much of your examples, the lowest notes are parts of octaves played in the left hand, so you only have to read the higher note of the octave and then place your fourth or fifth finger an octave below your thumb.
Comment: Once again, I note that there is no good reason to use _8vb,_ because the "a" in _8va_ does not stand for _alta._
Comment: @phoog I don't disagree with you. Still, major publishers like Hal Leonard continue to use "8vb" to indicate octave below, even for recent works. I assume it's just one of those conventions that doesn't make sense but the fact that it doesn't make sense doesn't stop it from being popular.
Comment: @phoog Maybe you should direct your views on the matter to Hal Leonard or Schott?
Comment: I passed my Royal Conservatory of Music Grade 10 piano performance and failed my ARCT with a score in the 70s. If reading 5 or more ledger lines was that essential, my piano teachers sure didn't pick up on that.
Comment: @phoog A German publisher, Schott, has decided that the "va" is unnecessary, but that the "b" clarifies which direction the octave is shifted. They use "8" above the staff with a line of octave up and "8b" below the staff for octave down. Seems like there's a consensus (for whatever reason) that the position of the mark and line is not sufficient to confirm the direction of octave shift.
Comment: @ToddWilcox that publishers like Hal Leonard are willing to do violence to the Italian language does not make it right. Has anyone _ever_ written an octave transposition above the staff and indicated that it was a downward transposition by using "b" or any other means? Has anyone _ever_ done the opposite? It's a solution looking for a problem. The position of the mark was sufficient for a couple of centuries; I don't think we're that much less intelligent than our forebears. Does any Italian or other romance-language publisher follow HL or Schott? I doubt it; they know that a != alta.
Answer: Read the top pitch of the bass part and then read the ledger lines below as intervals.
Ex. If I know that two ledger lines under the bass is C and then the interval under that C is a sixth, then I know the lower note is an E.
In your examples most of the reading by interval of the lower note is easy, because the interval is pretty consistently an octave. Below is how to do it. The red line traces the top of the bass, all the notes below are at the octave, except the two places where a perfect fifth is added inside the octave.
In blue I circled the two lowest occurrences, one with the top note on a line and the other on a space. Notice that the octave reading is a count of four lines. That's my quick way to recognize an octave.
It's so common to double at the octave in a bass part that you almost don't read it note for note. A quick spot check confirms a passage in doubled octaves.
Regarding too many ledger lines below the staff, it is not too many if you orient from the top bass note.
Comment: "It's so common to double at the octave...": absolutely.  I wonder if there is any piece that has parallel sevenths, ninths, or tenths in this register.  I'd be surprised.  But if there is, I bet they are written over an ottava bassa instruction.  Otherwise, players would tend to assume that they were octaves, because, indeed, one doesn't really read the bottom notes.


Central Projection of the Sphere

Question:
Given the parameterization of the unit sphere $x^2+y^2+z^2=1$ as
$x = \displaystyle\frac{u}{\sqrt{1+u^2+v^2}} $
$y = \displaystyle\frac{v}{\sqrt{1+u^2+v^2}} $
$z = \displaystyle\frac{1}{\sqrt{1+u^2+v^2}} $
Find $ds^2=dx^2+dy^2+dz^2$ and using the metric computer the area of
  the hemisphere $z\geq0$

I got:
$dx = \displaystyle\frac{v^2+1}{(u^2+v^2+1)^{3/2}}du-\displaystyle\frac{uv}{(u^2+v^2+1)^{3/2}}$dv
$dy = -\displaystyle\frac{uv}{(u^2+v^2+1)^{3/2}}du+\displaystyle\frac{u^2+1}{(u^2+v^2+1)^{3/2}}dv$
$dz = \displaystyle\frac{-u}{(u^2+v^2+1)^{3/2}}du-\displaystyle\frac{v}{(u^2+v^2+1)^{3/2}}dv$
And
$dx^2+dy^2+dz^2= \displaystyle\frac{(v^4+2v^2+1+u^2+u^2v^2)du^2+(u^4+2u^2+1+v^2+u^2v^2)dv^2+(-2uv-2u^3v-2uv^3)dudv}{(u^2+v^2+1)^3}$
But I can't see an obvious simplification
Comment: Spherical coordinates are for spheres. I gather you may not have such freedom here. That said: notice that you can factor the $dudv$ term $-2uv(1+u^2+v^2)$. I'm not totally sure your multiplication is correct (I've not checked it all)
Comment: yes i have to deal with a certain parameterization, but using Sashsa' factoring has given me what i needed to finish the problem, just checking over a few more things though
Answer: Factor your coefficients:
$$
    v^4 + 2 v^2 + 1 + u^2 + u^2 v^2 = (1+v^2)(1+u^2+v^2)
$$
$$
  u^4 + 2 u^2 + 1 + v^2 + u^2 v^2 = (1+u^2) (1+u^2+v^2)
$$
$$
   (-2 u v-2 u^2 v-2 u v^3) = - 2u v(1+u^2+v^2)
$$
Then cancel common factors of the numerator and the denominator.
Comment: After I've calculated $ds^2$ and $da$, the area element, I'm having trouble finding the bounds in which to integrate.
Comment: If you mean to integrate over the hemisphere, then $u$ and $v$ are unconstrained, that integrate over $(u,v) \in \mathbb{R}^2$.

Central Projection of the Sphere


Is there $b$ depending only on $a$ such that $\prod_{i=1}^n \Gamma(\lambda_i a) \le b$ for all $\lambda_i >0$ s.t. $\sum \lambda_i = 1$?

Question: Consider the Gamma function
$$
\Gamma(x)=\int_{0}^{\infty} t^{x-1} e^{-t} \mathrm d t \quad \forall x>0.
$$
From this Wikipedia page, I get for all $x_{1}, x_{2}>0$ and $t \in[0,1]$,
$$
\Gamma\left(t x_{1}+(1-t) x_{2}\right) \leq \Gamma\left(x_{1}\right)^{t} \Gamma\left(x_{2}\right)^{1-t} .
$$

Now we fix $a>0$. Is there some upper bound $b$ depending only on $a$ such that
$$
\prod_{i=1}^n \Gamma(\lambda_i a) \le b \quad \forall \lambda_1, \ldots, \lambda_n >0 \text{ s.t. }\lambda_1 + \ldots \lambda_n = 1?
$$
Answer: No. Since $\Gamma(x)\sim \frac1x$ as $x\to 0$, taking $n=2$, $\lambda_1=\epsilon$ and $\lambda_2=1-\epsilon$ gives
$$\prod_{i=1}^2\Gamma(\lambda_ia)=\Gamma(a\epsilon)\Gamma(a-a\epsilon)\sim \frac{\Gamma(a)}{a\epsilon},$$
which is arbitrarily large as $\epsilon\to 0$.


Criar uma combinação aleatoria com classes CSS utilizando javascript ou jquery

Question: Fala galera, queria saber se alguém sabe alguma solução de como fazer uma combinação de classes css utilizando javascript ou jquery?
O que gostaria é tendo links e cada um desses links tivessem varias classes de cor, e após selecionado algum dos links gerasse uma pagina com com um bg de uma cor e que a font fosse de outra, que seja sempre aleatória para cada pessoa que clicar, pois isso será usado como um tema para sites gerenciados que estou montando.
Comment: Cria uma array de classes e depois usa-as aleatoriamente. Mas podias/devias fazer isso no servidor acho eu. Que linguagem tens no servidor? já tens essa lista de classes?
Comment: Não tem essa lista não, isso é um projeto que gostaria de estar implementando, tenho todas as linguagens no servidor porém a preferencia seria em js ou jquery se possivel
Answer: Você pode sortear as classes de uma array. Ou melhor, duas, uma para o BG e outra para a fonte, assim você garante algum contraste. Exemplo:

var classesBg = ['fundoAzul', 'fundoVermelho', 'fundoVerde'];
var classesTexto = ['textoBranco', 'textoPreto', 'textoCinza'];
function sorteia(arr) {
    var rand = Math.floor(Math.random() * arr.length);
    return arr[rand];
}

document.getElementById('troca').addEventListener('click', function() {
    var classeBg = sorteia(classesBg);
    var classeTexto = sorteia(classesTexto);
    var elemento = document.getElementById('conteudo');
    elemento.className = classeBg + ' ' + classeTexto;
});
.fundoAzul {
  background-color: #0000ff;
}
.fundoVermelho {
  background-color: #ff0000;
}
.fundoVerde {
  background-color: #00ff00;
}
.textoBranco {
  color: #ffffff;
}
.textoPreto {
  color: #000000;
}
.textoCinza {
  color: #aaaaaa;
}

Texto texto texto

<button type="button" id="troca">trocar</button>
Comment: Isso, experimente brincar um pouco com esse código.
Comment: Cara, a array aqui é de classes. Isso que você linkou é um script que gera um código de cor aleatório, é diferente. Se quiser usar esse script, altere as cores do elemento diretamente, em vez de trocar classes (que era o que você tinha perguntado). Por exemplo: `elemento.style.backgroundColor = randomColor()` (inclua o script antes como explicado no site deles).
Comment: Cara, isso tá indo além do escopo desta pergunta. Tente montar um exemplo simples do problema e poste como uma pergunta à parte.
Comment: E como eu poderia fazer para que cada um dos links gerasse uma paleta de cor diferente, tipo romantico use cores vermelhas e rosas, feliz use tons amarelos e azuis?
Comment: Crie arrays diferentes para cada paleta.
Comment: usando esse código então faz com que crie temas diversos dentro das cores que eu estipular, e que aquele bg e aquela cor da font fique fixo em cada tema por exemplo?
Comment: Vlw cara, estou atras disso faz mais uma semana e meia
Comment: Como que eu faço para que ele abra a pagina nova com a combinação, pois coloquei o blank no botão porém ele abre a pagina sem classe nenhuma.
Comment: Aí já é mais complicado, e foge da sua pergunta original. Você pode salvar num banco de dados e ler de lá, ou pode salvar na máquina da pessoa (num cookie ou localstorage). Sugiro abrir uma pergunta separada sobre isso.
Comment: Sabe se tem como eu colocar um imagem e só apareça no "tema" selecionado?
Pois eu peguei seu codigo e tripliquei ele fazendo com que tenha 3 tipos de tema
Comment: Se você colocar a imagem no CSS, como background-image, não resolve?
Comment: Então é que o que eu queria era ter uma imagem em parallax, pois como faço o parallax em puro css.
Para as imagens que não terá o parallax eu usei o bg mesmo.
Comment: Ah blz, é que como passou o código pensei que soube-se alguma maneira, mas vou montar uma pergunta com isso, vlw


Counterexamples of integral convergence

Question: Suppose that a sequence of integrable function $(f_n)$ converges uniformly to the zero function. I want to find an example of such $f_n$ exhibiting the property that $$\int f_n \not \to 0.$$
What if we replace uniform convergence with uniformly bounded and point wise convergence?
Comment: You should specify the limits of integration. If you integrate over a compact interval then you won't find such example. If you integrate over an unbounded one then there are examples.
Comment: @NeedForHelp Thanks, but that still doesn't help me too much
Comment: Have a look [here](http://math.stackexchange.com/questions/24171/lebesgue-integral-uniform-convergence) for a start.
Answer: Does $f_n=\frac{1}{n}\chi_{[0,n]}$ work?  The integral of all these are $1$, but they converge uniformly to the $0$ function.
If you want a compact domain (or even just a finite measure domain), and your functions $f_i$ are uniformly bounded and pointwise convergent, then you use Dominated Convergence theorem on the constant function that bounds them all.
Also, I don't know why your bounty answer needs to draw from a credible or official source.  If you believe and understand the answer, why does it matter where it comes from?
Comment: Try a bump function on $[0, 1]$ and then translate it to the right by $1$ repeatedly.
Comment: What if I want a finite measure domain, point wise convergence of $f_n \to 0$, but not necessarily uniformly bounded?
Comment: Counterexample: take a bump function on $[0, 1]$, and then dilate it by $\frac{1}{2}$ in the $x$ direction and $2$ in the $y$ direction, and repeat.
Comment: @user3359 On $(0,1),$ let $f_n(x) = nx^n.$ Then $f_n\to 0$ pointwise on $(0,1),$ yet $\int_0^1 f_n = n/(n+1) \to 1.$
Comment: @BobJones Can you give me an example of where the convergence is point wise, not uniform, but the functions are uniformly bounded? I'll then be happy to award you the bounty.
Comment: @BobJones What will the integral of the bump function converge to?
Comment: Whatever the integral of the original bump function is. It's constant.
Comment: @user3359 Why did I not receive the full bounty?  Did you forget to accept, or were my answers not to your satisfaction?

Counterexamples of integral convergence


How to prove Cantor's theorem by assuming an injection $g ∶ P(A) \to A$ and then arguing to a contradiction

Question: Considering the set, $D = \{x ; (\forall\ x\in A)(\exists\ Y\in P(A))(g(Y)=x, x\notin Y)\}$. We then assume $g$ is an injection, how does one argue to a contradiction?
Comment: I want to prove it in this particular way, yes there are easier ways to prove Cantor's theorem, but in the problem I am struggling with there is a way to prove it as stated.
Comment: Try to check whether $g(D) \in D$ or $g(D) \not\in D$. Bot possibilities lead to a contradiction, and then you are done.
Answer: If $g(D) \in D$ then by the definition of $D$ there exists $Y \in P(A)$ such that $g(Y) = g(D)$ and $g(D) \not \in Y$. But $g$ is injective hence $Y = D$, so $g(D) \not \in D$ and we have a contradiction.
On the other hand if $ g(D) \not\in D$ then in particular there exists $Y \in P(A)$ such that $g(Y) = g(D)$ and  $ g(D) \not\in Y$  (namely $Y = D$). This means that $g(D) \in D$ by the definition of $D$, which is again a contradiction.
We must have one of these two possibilities, so $g$ cannot exist.


View com muitos, mas muitos case when's

Question: Estou montando uma view no banco de dados que a view pai usa como consulta outra view, que por sua vez chama outra view (nessa view é feito a soma de vários itens e traz o total por linha), na view 'de fora' é pego as contas (por número) e jogo um nome para cada conta, exemplo:
case when conta = '1' then 'chamar desse nome'

Mas isso ocorre umas 30 vezes na view, já que temos várias contas, e na 3° view que chama esta, ele junta várias contas, mas usando o nome dado na view anterior, então fica mais ou menos isso:
case when conta in ('alugueis', 'agua', 'luz') then ('grupo despesa')
Só que são muitas contas, e muitos grupos, chegou em um limite onde o SQL me deu limite de complexidade atingido, sabem o que pode ser feito para corrigir?
Vou postar um trecho da 3° view aqui para exemplificar:
case
when (a.num_conta between '1.1.01.001.0001' and '188.8.131.529.9999') then 'TOTAL ATIVO'
when (a.num_conta between '2.1.01.001.0001' and '188.8.131.529.9999') then 'TOTAL PASSIVO'
when (a.num_conta between '2.1.01.001.0001' and '220.127.116.119.9999') then 'TOTAL PASSIVO'
when (a.num_conta between '3.1.01.001.0001' and '22.214.171.1249.9999 ') then 'TOTAL RESULTADO' end as 'TC',

case
when (a.NUM_CONTA between '1.1.01.001.0001' and '22.214.171.1249.9999') then '1 - ATIVO CIRCULANTE'
when (a.NUM_CONTA between '1.2.01.001.0001' and '188.8.131.529.9999 ') then '2 - ATIVO NÃO CIRCULANTE'
when (a.NUM_CONTA between '2.1.01.001.0001' and '22.214.171.1249.9999 ') then '3 - PASSIVO CIRCULANTE'
when (a.NUM_CONTA between '2.2.01.001.0001' and '126.96.36.1999.9999 ') then '4 - PASSIVO NÃO CIRCULANTE'
when (a.NUM_CONTA between '2.4.01.001.0001' and '22.214.171.1249.9999 ') then '5 - PATRIMONIO LIQUIDO'
when (a.NUM_CONTA between '3.1.01.001.0001' and '188.8.131.529.9999 ') then '6 - RESULTADO DO PERIODO' end as tipo,
case when (a.tipo_conta in ('01 - CAIXAS E BANCOS', '02 - APLICAÇÕES FINANCEIRAS','03 - NUMERÁRIOS EM TRÂNSITO')) then '01 - TOTAL EQ CAIXA'
   when (a.tipo_conta in ('01 - CLIENTES','02 - BANCOS CONTAS VINCULADAS','03 - TITULOS DE CAPITALIZAÇÃO','04 - ADIANTAMENTOS','05 - IMPOSTOS A RECUPERAR','OUTROS CRÉDITOS - CHEQUES DEVOLVIDOS','07 - MERCADORIAS EM TRANSITO ATIVO','08 - MUTUO NEWFER','09 - ADIANTAMENTOS PROJETO NEWFER')) then '02 - DIREITOS REALIZAVEIS'
   when (a.tipo_conta in ('DESPESAS EXERCICIO SEGUINTE')) then '04 - DESPESAS DO EXERCICIO SEGUINTE'
   when (a.tipo_conta in ('ESTOQUE')) then '03 - ESTOQUE'....

Comment: Não sei qual SGBD você está utilizando mas já avaliou o uso de CTE (Common Table Expressions) com WITH?
Comment: Primeiro que você não precisa de between, pode pegar simplesmente os caracteres antes do segundo nivel (1.1, 2.1, 3.1 etc) e fazer uma comparação dirata. Por sinal me parece ter problema o formato que usou no campo (por exemplo, o que fazem os pontos dentro da string? se a largura é fixa, está armazenando coisa espúria, se não é fixa, o between não vai funcionar de qq forma)  - segundo que não devia ter essas strings no SQL e sim numa tabela separada (seja em SQL ou na sua aplicação). A resposta do @maniero os principais problemas na maneira que está aplicando sua lógica.
Comment: não conheço essa funcionalidade amigo, vou dar uma pesquisada pra ver, consegui rodar eliminando alguns 'case whens' desnessários, mas é como o amigo acima falou, quanto mais contas forem entrando, terei que alterar e adicionar mais condições e logo vai estourar novamente
Comment: @RafaelS. A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Não era para usar CASE, deveria ser uma relação com JOIN ou alguma outra forma que estabeleça isto, em último caso usar uma stored procedure (isso parece errado ainda), inclusive porque isso não é algo fixo, se alguém mudar uma descrição, uma numeração de item, ter novos dados, ou sair algum, é algo discricionário do usuário ele terá que pedir para você mudar o código e se não mudar na hora a aplicação para de funcionar corretamente. A solução é pegar esses dados de uma outra tabela, e espero que já tenha ela, caso contrário tem vários outros problemas. Se não tem terá que pensar nisso, não pode resolver um problema de arquitetura e modelagem de dados ruim com uma gambiarra em código. Tem que ter uma parametrização desses agrupamentos.
O CASE serve para usar com algo muito estável e que nunca tenha que mexer, além de ser algo curto, você está transformando dado em código, isso tá errado. O ponto principal é que o CASE é o mecanismo errado, tem que arrumar a modelagem. Mesmo que tenha uma solução no código que não envolva refazer a modelagem será gambiarra.
Comment: A sua pergunta é sobre o `CASE`, e não tem como fazer isso desta forma. De fato não deveria fazer isso no Excel, tem que remodelar seus dados para que possa juntar tudo isso com `JOIN`, isso você não está está fazendo com `JOIN`, está fazendo com `CASE`. Eu consigo visualizar menos que você afinal você conhece o software que está trabalhando, eu não, só posso falar do que eu vi, e vi algo errado de se fazer, está usando `CASE` para algo que ele não foi criado.
Comment: Entendi, mas qual seria a opção então?

Pois nesse caso, não encontrei outra forma de fazer, pois eles precisam pegar contas ja existentes, agrupar e nomear os grupos, para entao trazer em um BI, hoje, não temos os nomes prontos no programa
Comment: A que eu escrevi na resposta.
Comment: mas ja utilizo de joins para juntar varias tabelas, o meu problema seria mesmo jogar varias contas, em grupos passados pelo usuário, pois a ideia é ter uma analise pronta, sem ter que todo mes pegar conta a conta, jogar no excel e montar isso, não consigo visualizar outra forma de fazer sem utilizar 'case when'...

View com muitos, mas muitos case when's


Playing a song in a different key

Question: I trying to teach myself guitar and one song I want to perform for a friend (soon) is Akon's "Don't Matter." I can't read sheet music (but i want to learn) but i found the chord progression of the song. It is A-E-F#m-D, from some research I discovered that this is the stereotypical pop-punk chord progression I-V-vi-IV.
But I am just a beginner at guitar and have a lot of trouble with F chords due to my smallish hands and lack of experience.
I don't know any music theory but i know that the key of a song can change and it should still be recognizable as that song (though this is a mystery to me because i don't really understand the concept of key).
If I play this is the key of G the chord progression becomes G-D-Em-C which is a lot easier for me to learn and play.
I am wonder how exactly this affects how one hears the song, how does changing the key change how you hear it and perceive it? What exactly is key and why is it important?
And lastly, if i try to sing this song while playing it do i have to sing it differently if i change the key?
Comment: This clip uses the (extremely common) progression you are playing and answers some of your questions http://www.youtube.com/watch?v=oOlDewpCfZQ
Answer: What does changing key mean?
Changing key means you need to sing slightly higher or lower. For example try this chord progression (La Bamba, or most of Twist and Shout, or many other songs.)

    Key of C: Chords C F G
    Key of G: Chords G C D
    Key of D: Chords D G A
    Key of A: Chords A D E
    Key of E: Chords E A B

Any of these will work. The reason the song is still recognisable is because the relationship of the notes has not changed. (they are ALL raised/lowered by the same amount.) In all cases we have three major chords, starting with the I of the scale, then the IV (5 semitones/frets up from the I) and then the V (7 semitones/frets up from the I.)
These patterns are somewhat disguised by the different fingerings you have to do to keep the
chords near the nut, so try the following in order to see it more clearly (don't bother with the 1st and 5th string if you can't manage the bar chord. If you are using a pick or strumming with your thumb it's a good idea to rest a finger of your right hand on the 1st string to silence it.)

    Key of G      Chord G   C   D

                  e-----X---3---5
                  B-----0---5---7
                  G-----0---5---7
                  D-----0---5---7
                  A-----X---3---5
                  E-----X---X---X

Now add 2 to each of the numbers in the above tab and play again. Now you're playing in A (chords A D E.)
What is a key? (a simple explanation for strummers)
There are many ways to say what key is, but one of the most useful is to identify which chords belong to each key (that doesn't mean you can't play others, but it helps you to know which are most likely, and any that don't belong will stand out to your ear as being unusual.)
Another very useful thing is the cycle of fifths, which is covered elsewhere and you should learn all you can about. It's basically a series you get by going up 7 semitones/frets at a time. Here it is in brief.
    Gb Db Ab Eb Bb F C G D A E B F# C# G# D# A#
And here's the same thing in a zigzag (which is easier to remember because the notes on each line are consecutive, but is not as fundamental in concept.)

    Gb  Ab  Bb   C   D   E   F#  G#  A#
      Db  Eb   F   G   A   B   C#  D#

You probably know that every major key has a relative minor key, for example C major / A minor. It's easy to pick out the chords that belong to this or any key from the cycle of fifths, according to the example below.
The root notes of the three major chords of C major fall consecutively in the circle of fifths: F C G with the C in the middle.
The root notes of the three minor chords of A minor fall in a similar pattern: Dm Am Em with the A in the middle.
As I said A minor is the relative minor of C major, and additionally you will note F C G is followed immediately by D A E the cycle of fifths. So you will find that many songs use exactly this group of 6 chords F C G Dm Am Em and those are the songs in the key of C.
I hope this is useful to you in knowing which chords belong to a key.
As I say, these are the basic rules, but musicians are free to break them (and nearly every exception to the rule is well studied and has a name.) The most common change (so common I can't even call it bending the rule) is the sustitution of a minor chord by its major version.
Comment: I write an answer, review it on my screen, it looks lovely, with nice grey boxes of text. Then I post it and SUDDENLY it interprets all my single notes as chords and starts shoving chord boxes everywhere (and not necessarily the fingering I wanted even when there were chords.) So I have edit to bastardise my nice formatting. Please Mr Computer, print what you showed me when I was editing or Leave Well Alone!
Comment: @user2237160 Two things: Feel free to upvote; And study that circle of fifths, the basis of harmony (supposedly invented by Pythagoras the triangle guy.) Most songs have chords selected from 6 consecutive notes on that list, three major then three minor (though the song may not use all 6 and may change some that "should be" minor into major.) If all you want to do is strum, then that set of 6 chords is a good working definition of what the key is.
Comment: Your 3rd para, starting with 'these patterns'. The thinnest string is the first string. Why would that need to be muted? If you mean the lowest (fattest), then how do you mute that with a finger whilst strumming with the thumb?
Comment: @Tim this is for an absolute beginner. Note the entire parenthesis: `(don't bother with the 1st and 5th string if you can't manage the bar chord. If you are using a pick or strumming with your thumb it's a good idea to rest a finger of your right hand on the 1st string to silence it.)` i.e when reducing an A shape to just 2nd 3rd and 4th strings because you can't bar properly, little or ring finger on the 1st string prevents a downstrum going too far.
Answer: A simple way round this is using a capo. Put it on fret 2, and use your suggested chords of G,D, Em, C. It will put you into the original recorded key. However,because the voicings of each of the chord have now changed, it will sound a little different. Not wrong, just different.
Putting the capo on fret 5, you could use E,B7,C#m and A, the troublesome one being C#m maybe. Or capo 8 and use C,G,Am,F. There's going to be a barre chord again !
Moving a song up or down by a tone or semitone will probably not cause many listeners concern - most wouldn't notice This topic has been discussed many times on this site.
The bottom line for you, I'm sorry to say, is to learn your barre chords, as then you'll be able to play any song in any key in any place on the guitar. If you're finding it really uncomfortable, get the action checked.It may be too high for you.
Yes, you will have to sing it differently, but once you start playing the new chords, your voice will adjust automatically. Don't worry about that.
Comment: Capo is one solution, but playing open position chords on an acoustic guitar often sounds nicer than barré/capo (in my opinion), so the transposition could have a point in itself.
Comment: A good capo, well applied, ought to give an 'open string' sound to whichever fret it's applied, at least up to 5 or 6.One could even down tune by 2 frets and put the capo on fret 2, - would most people notice ?
Answer: Yes, you have to sing it differently when the key changes. Higher or lower in pitch. the range of the singer or instrument to play the melody is one of the primary reasons for you to change key. If the song is not so guitar based (i.e. Dust in The Wind, Stairway to Heaven) the key change should not affect how it sounds but that is for you to judge. You could also play it in G and use the capo in second fret to maintain the original key. Or you could use a simplified version of the F chord without the barre.
Answer: Due to the different voicings of guitar chords in open position, a song can sound quite different when played in different keys. But if one uses a capo to change key, then this effect is lost.
Depending on the range of notes (tessitura), changing the key can also be very important for the singer. It may mean the difference between being able to sing the song and not being able! There have been several questions here on this topic.
Most people have relative pitch - they can tell what the notes of the scale are, but not what the absolute pitch is. Thus for these people, changing the key won't matter too much. There are some (lucky?) people who have absolute pitch, thus for them, changing the key will make a difference.
Of course, some people are tone deaf....
Comment: first para - the effect may be lost, but if that capo is more than 5 or 6 frets away from the nut, the chords will not sound too similar.Maybe to the tone deaf...
Answer: G is just a whole tone down from the original key of A. That corresponds to going from fret 5 on the low E string to fret 3 on the same string. You would have to sing it one step lower in order to transpose the whole song. (Playing the song in G while singing it in A will create some interesting harmony though...)
Since it is just a whole step, this transposition will likely not be noticed by most people.
Answer: Music is really a relative thing - if you think in terms of 4th, 5th, 3rd etc from a root note, that's how it really works. within a limit, songs played a few tones either side of their original recorded key will sound the same.
you can see this in operation in an instrument (say a guitar) - if it's not tuned to the universally agreed "concert pitch", but is in tune with itself (ie, the musical interval between the strings is as it should be) then tunes played on it will sound fine.
If you then tried to play that non-concert-pitch guitar along with another instrument which IS tuned to concert pitch, the two will mismatch and not agree on what pitch a "C" is (for example)
Lots of older records were recorded not at concert pitch- the whole band were tuned just slightly flat or sharp (because before digital stuff came out, tuning wasn't such an exact science and more open to human/technical error), but it's ok because they were all tuned with each other so it sounds fine.
The concept of "Concert pitch" is that it's an agreed frequency for certain notes to be. Eg an A is 440 cycles per second. Digital tuners are calibrated to this, so if you tune your guitar with a modern tuner it'll be set up to the universally agreed standard, and you'll immediately sound in tune when playing with other musicians tuned to concert pitch (er assuming you're playing the same thing haha)
The "Key " of a song is just the starting point for the chords/melody to start - if you think of the I-V-vi-IV sequence, it's a relative thing describing intervals based on a starting point, and the key just defines the starting point.
(Though be aware that some songs start and 'resolve' to a key which isn't the starting chord - eg Back in the USSR by the Beatles starts in E7 but resolves such that the whole song is in A)
Regarding singing : one of the reasons that people change the key of a song is so that it's easier for them to sing- some people can sing higher than others (wonem have a higher range than men), and not everyone cxan reach the high/low notes involved in some tunes. So you can just slide the starting point up or down in pitch a bit to suit your voice.
Will you have to sing it differently ? Yes-  the tune will be the same relative to the new chords you're playing, but it'll be slightly lower. You'll probably find that when you start playing it you can sing it straight away- humans are pretty remarkable like that :-)
Answer: I struggle with this all the time with singers, my 2 cents is you are doing a cover tune and a cover tune is suppose to be done like the recording if you want to change it and do your version of it then by all means do that but DO NOT call its cover, when you change keys of songs you mess with the over all tone and the feel of the song for me I hate going to see a cover band and they don't play anything in the right key to me you are not a cover band, cover bands cover songs like the CD. Just my 2 cents, carry on
Comment: So, a song is written, and recorded by several people/groups, in different keys. Which is the 'authentic' one?  Unless one has absolute pitch, one won't usually be able to tell whether the key is correct - unless one knows the song, can play it, and is there watching the performance. Even then, the band may be tuned down!  This doesn't particularly answer the OP's question, and doesn't make much sense - maybe 2 cents! Welcome to the site, but please read the ins and outs of what makes good answers.
Comment: Some bands play their own songs in different keys on different recordings. I don't think it makes the songs worse at all. But I agree with Tim that this doesn't answer the question very well.
Answer: You can play a song in any key, and it sort of sounds the same, except for being higher or lower in pitch.
However, some keys are easier to play on particular instruments. On a guitar, playing a C chord is relatively easy, but playing an Ab chord requires a barre and is more difficult. Picking out a melody in the key of G, A, or D for example is much easier on a guitar than in Bb or C# say.
But on a Bb clarinet, it's Bb that's easy.
On a fiddle or mandolin, and playing Celtic (Irish & Scottish) music, most tunes tend to be in D, G, A, Am, Em and a few others, because it's easy to play. Keys like B are hard to play in, so there aren't many tunes in that key.
Comment: Sometimes, using barre chords in a piece that needs damping for the rhythmic pattern, they are easier to use to get the effect than playing open chords, which are not particularly easy to damp, having open strings. Picking out a melody in G,D or A probably involves some open strings, which sound different from the fretted ones, so the tune doesn't sound so level, tone wise. Using all fretted strings solves that - and vibrato can be used on any - difficult with open strings.
Answer: Different keys really have different personalities.
If you really want to experience a change in feeling, transpose your song in A to the key of E-flat.  That big distance from A to E-flat will make my point vividly.
Using the formula you gave us of I-V-vi-IV, that chord progression in E-flat is
Eb-Bb-Cm-Ab
Yes, understandably for guitar, sometimes the flat keys are more difficult to deal with than the sharp keys.  Nevertheless, try it.
Or if you have a musician friend who's played for a while, ask them to play the 2 chord sequences in A vs. E-flat to hear the difference.  (You'll definitely hear the change in mood on a piano, organ or other keyboard instrument where you can play the chords fully, esp. with roots.)
Since you asked about singing, that's one big reason knowing how to change key is important.  You may be asked to accompany a vocalist with your guitar.  The singer has their range, and they will feel more at ease in another key.  Apparently you've experienced this already in deciding to lower this song from A to G.
If you really want to explore this concept of key, go for all 12 major keys.  When we first learn to transpose, it helps a lot to write it down.  Go ahead and fill in the chords for starting out on A, Bb, B, C, etc.
Also, take note of the different senses.  In addition to hearing the chords, what do they look like with your fingering?  What does your hand position and touch feel like?  And are there any keys you tend to like more than others?  While ideally we'd like to be proficient in all keys, we do have our personal favorites like ice cream flavors.
Enjoy!
Answer: Lot of answers, but what I think you're looking for is a simple answer that makes intuitive sense.
Keys are just a set of related numbers. They can change, but everything in the set remains the same, relatively.  Think simple first grade math:
Here is a set of 3 numbers -->> [ 1, 3, 5 ]
If you add 1 to each number you get [ 2, 4, 6 ]
Different set of numbers, but they all moved/changed the same -> by 1
Keys work exactly the same.  You can test and hear this for yourself w/o needing to use chords.  Just use root notes on the 6th and 5th strings.
..............................
Play:
E (6th string) -3---------
A (5th string) ---3-5------
Then play:
E (6th string) -4---------
A (5th string) ---4-6------
..............................
See how everything moves up 1 fret?  (You added 1, simple math)
It obviously sounds different, and that difference means a different key.  But the relationship of the notes sounds the same.  You could move that up 1 more fret and it would be a different key, but sound "the same"
E (6th string) -5---------
A (5th string) ---5-7------
Etc.  And keep going.  Keys are really that simple.
.........................................
Take a look at a keyboard layout to see how notes repeat.  In other words, tab really holds you back from learning music in the sense that say "6th string, 5th fret" doesn't mean anything except to other guitarists.
Keyboards don't have frets, so "6th string, 5th fret, then play 6th string, 8th fret" doesn't mean anything on piano. But, when you can understand and say, for example, "I'm playing an A, then a C" ->> this is something a piano player can understand, etc.

Playing a song in a different key


Recursividade- elemindices

Question: Sabem como definir recursivamente a função elemindices, pré-definida na Prelude.
Eu defini de uma forma, mas não dá o resultado esperado.
myElemIndices :: Eq a => a -> [a] -> [Int]
myElemIndices x [] = []
myElemIndices x (h:t) | x == h = 0 : myElemIndices x t
                      | otherwise = myElemIndices x t

Comment: Qual o resultado esperado?
Comment: elemIndices 3 [1,2,3,4,3,2,3,4,5] corresponde a [2,4,6].
Answer: Vou explicar duas formas que funcionam mas não sei se é realmente o que você deseja:
myElemIndices :: Eq a => a -> [a] -> [Int]
myElemIndices x [] = []
myElemIndices a xs = indexed a (zip xs [0..])
    where indexed _ [] = []
          indexed a ((x,i):xs)
              | x == a = i:indexed a xs
              | otherwise = indexed a xs

Estou usando uma função interna chamada indexed que atribui índices à lista usando a função zip. Essa função retorna tuplas com a união das listas, no caso fica (x1, 1), (x2, 2) ... (xn , n). A cada rodada recursiva em que a igualdade x == a é verdadeira eu faço o append do índice no resultado. (Veja no repl.it - créditos ao autor: Counting positions in a list haskell)
Ou pode fazer uso de uma função auxiliar diferente:
myElemIndices :: Eq a => a -> [a] -> [Int]
myElemIndices x [] = []
myElemIndices x xs = count 0 x xs

count :: Eq a => Int -> a -> [a] -> [Int]
count c x [] = []
count c x (y:ys)
   | x == y = c:count (c+1) x ys
   | otherwise = count (c+1) x ys

No caso acima eu uso uma função com um argumento a mais para contar. Quando x = y ele da um append no contador atual e passa adiante com contador + 1. (Veja funcionando no repl.it)
Comment: Muito Obrigado, era isso mesmo o que pretendia :)
Comment: Poderia marcar a resposta como aceita? Tem um OK verde ali embaixo das setas ^ | v

Recursividade- elemindices


armhf VM on amd64 with virt-install

Question: I'm trying to install a VM with armhf on an amd64 system with:
virt-install -n test2 -r 2048 --os-type=linux --disk ~/armhf.img,device=disk,bus=virtio,size=8,sparse=true,format=raw --os-variant debian10 --vnc  --location ftp://ftp2.de.debian.org/debian/dists/buster/main/installer-armhf/

This results in an error:
Starting install...
ERROR    Couldn't find kernel for Debian tree.
Domain installation does not appear to have been successful.
If it was, you can restart your domain by running:
  virsh --connect qemu:///session start test2
otherwise, please restart your installation.

What does this error mean in particular? How could I fix this?
Answer: The error means that virt-install doesn't know where to grab a kernel from that URL tree. This is possibly a virt-install deficiency but it's not clear to me if that URL is even an install tree, or just for netbooting.
If you are trying to boot a pre-existing disk image, you can try downloading the kernel and initrd manually from that tree, and passing them to virt-install --boot kernel=X,initrd=Y. But I'm not sure if the virt-install+libvirt combo has good support for booting these debian arm VMs, it may use incorrect defaults.
It may be easier to use qemu directly. Google gives me: https://translatedcode.wordpress.com/2016/11/03/installing-debian-on-qemus-32-bit-arm-virt-board/
(Also, use http://, it is much faster than ftp://)

armhf VM on amd64 with virt-install


Trouble reading roman numeral notation with flats

Question: I am working my way through an article on transformations in rock harmony, but I am getting stuck trying to read the author's roman numeral analysis.  I would really appreciate some help understanding how to read flattened roman numerals. Here is an example of what I mean:

Thank you!
Answer: TLDR;
a sharp or flat before numeral mean raise or lower the chord root from its normal diatonic spelling

In the usual Roman numeral analysis we have these conventions:
First we have to give a label for a key like E: for E major or Em: for E minor. Then we have these points...

capital numeral means major triad
lower case numeral means minor triad
'o' after numeral means diminished triad
'7' means a diatonic seventh above root
a sharp or flat before numeral mean raise or lower the chord root from its normal diatonic spelling

That last rule is the crux of your question.
In E major the diatonic chord of the sixth degree is C# minor and gets labelled vi.
In E minor the diatonic chord of the sixth degree is C major and gets labelled VI.
If the VI from E minor is used in E major the chord root is altered from C# to C natural. (This is called chord borrowing.) When in E major that change in the chord root is made explicit in the Roman numeral figure by using the flat to show the change of chord root: bVI.
The reason your book's example is confusing is because the key signature on the staff is E minor, but the analysis key shows E which is read as E major (it should be Em: to mean minor) and then the Roman numeral figures are labeled with flats which makes things seem like the assumed key is E major. Basically the labeling is a mess and it makes confusing the use of sharps and flats on Roman numeral figures.
As others point out, the book doesn't even label the chords as 7th chords!
The book seems sloppy.
@Tim makes a good point that Roman numeral analysis can be tricky with rock music. The real conundrum to me is the final chord. It's an E dominant 7th with a G natural on top. That is a very bluesy sound. It's a very familiar sound, but Roman numerals are a poor way to label it. There is no way to indicate the simultaneous G# and G natural... and the minor 7th. About the only thing the I label gets right is a root on E and a perfect fifth of B. Tread carefully with harmonic analysis of rock music. You might find a lot of inappropriate labels.
Comment: Using the 7#9 is a common way to fit the blues major-minor chord into roman numeral analysis. In equal temperament, the distinction between a double sharp 2 and a flat 3 become less important. The notes are the same, so they are named either for function or even convenience.
Comment: Thank you for the great response!  Your answer was very clear--I appreciate it!
Comment: That's the Hendrix chord. E7#9 So there's a 7th  - D, and a #9 - Fx, which isn't exactly G, more F##. Can't think of any RN that describes it!
Comment: @trlkly, `7#9` as in `E7#9` would be a jazz symbol rather than a Roman numeral symbol. But it is interesting the #9 in a dominant chord versus a flat (minor) third over a major triad. I think when I have seen the latter it has been for a tonic chord. I've not seen a rule stated, but #9 to me says 'dominant' and flat third over major triad sort of 'tonic'
Comment: Trouble is, in relation to this music example at least, the answer's wrong.  The example uses the 'mode-blind' convention of chord numbering.   Everything is named relative to E major, even if the tune's in E minor.
Comment: @LaurencePayne, I have four harmony text and they all have slightly different RNA conventions. I tried to summarize. I don't know a "mode blind" _convention_ other than using all upper case numerals regardless of major or minor.
Answer: The notation seems a bit confusing. The first chord is a D7 in the key of either E-Major or e-minor; the author isn't quite so clear.  The key signature indicates e-minor in which case the chord is VII (no flat needed.) If the author shows keys in ALL CAPS (which has been outdated since 1834), the chord VII7 but that disagrees with the single sharp signature. The author also leaves off the seventh indicator.
Perhaps we can assume the author uses E irrespective of Major or minor mode and that he leaves off the seventh.  This still leaved the bVII vs VII so it's still still. The (V) must mean the seventh of G.
The author shows a descending scale (the caratted numerals above some of the chords) so perhaps that may help. I think he's using the Roman numerals associated with E-Major but the score is written as e-minor; he's assuming that all chords have sevenths (OK, but limiting). Then we have (if the score were in e-minor): VII7, VII7, VII7, VI7, III, VII7, VI7, V7, IM7 (at  least as I would notate it.)
Comment: Your 3rd line - did you mean 'chords' not 'keys' in ALL CAPS?
Comment: You'e right; I meant chords, not keys. It's harder to read Roman numeral analysis with all cap chords. Older versions of Piston's Harmony do this. Marx's 1830s book does use more modern notation and is easier to read.
Answer: Are you confused because the song's in E minor, but the Roman numeral chord names are relative to E MAJOR?    Yes, that's how it works.  The numbers only care that E is the tonic.   E minor triad is i, E major triad is I.   The uppercase Roman number doesn't mean 'diatonic', 'in key' or 'correct',  it just means 'major'.
Similarly for modified numerals.  G is the 'correct' third note of E minor, but G B D is called ♭III. That's ♭ because G is the flattened 3rd of E major, III because it;s a major triad.
G B♭ D would be ♭iii. That's ♭ because it's built on the flat 3rd of E major, iii because it's a minor triad.
I repeat, these names would be the same whether we were in E major, E minor or E anything-else.
Answer: RNA isn't designed for analysing 'rock' music. It sort of works when non-diatonic chords need naming, as we use 'b' in certain circumstances. As in key E. There is no D and no C, only D# and C#. So, we have to call the D chord bVII and C chord bVI. It gets as close as we can.
The bIII represents G, again because there's no G in key E: G# is iii (III) but we need the flattened G#, making G. Thus bIII.
Answer: The trouble is:
The key sign is G-major/e-minor:
 (in e-minor  the flat should be a natural sign to explain the  VI and VII degree are not of the harmonic scale!)
Indeed this progression is notated in respect of E-major!
D - D - D - C - G - C - D - E
If you transpose this figure to C you will understand that the flats are concerning
Bb - Bb - Bb - Ab - Eb - Ab - Bb - G - C (with the blue note b10)
Comment: 'In Em, the flat should be a natural sign...' I don't understand!
Comment: As in e-minor (harmonic and melodic key) the VII is D# a flat wouldn't be quite the chorrect sign, in my opinion there should be the sign the accidental corresponding to D natural).
Comment: Except we don't necessarily expect E minor to have D# - it could well be D nat. Although using the major as a datum point, D# would be the diatonic. But diatonic doesn't feature well in rock music, so RNA is never going to be a good idea.
Comment: RNA is roman numbers? Yes, I agree. To me it's only useful  for historical interests. The Chord signs will fit here better.
Comment: *Except we don't necessarily expect E minor to have D*. Have you seen the remark below the time 4/4? it says E:  (if this means E-major the VII and VI would be D# and C#.
Comment: RNA= Roman Numeral Analysis. Response to last comment - really don't know why some folk write out blues in that way. Unless it's minor blues - which this obviously isn't! It doesn't help anyone.
Comment: So I've learnt the RNA and the chords, I'm not so used thinking in the theory and abbreviations of Riemann and Maler. At the time I'm reading the Harmonielehre of Dieter De la Motte. https://en.wikipedia.org/wiki/Function_(music)


Problemas com alocação dinâmica

Question: Em um exercício preciso fazer um cadastro de uma struct possivelmente declarada como segue abaixo.
typedef struct Locatarios {
    char nomeLocatario[MAX_NOME];
    int codigoLoc;
    float valorAluguel;
} Locatarios;

É preciso utilizar alocação dinâmica para cadastrar um locatário por vez, então não se pergunta antes quantos serão cadastrados. Fiz assim:
Locatarios *pLocatarios;
pLocatarios = malloc(sizeof(Locatarios));

Até onde eu compreendo, a alocação funcionou perfeitamente e o cadastro está funcionando. O que eu não consigo compreender como fazer é que codigoLoc não pode ser repetido enquanto se faz cadastros.
Como eu percorro uma estrutura que foi alocada dinamicamente em busca de um valor?
Segue abaixo a função que realiza a pesquisa;
int verificaCodigo (int *codigo, int *contador) {
// Declarações locas
    Locatarios *pLocatarios;
    int aux = 0, totalLocatarios = 0;
// Instruções
    totalLocatarios = (sizeof(pLocatarios) / sizeof(pLocatarios[0]));
    pLocatarios = malloc(sizeof(Locatarios));
    if (pLocatarios != NULL) {
        for (aux = 0; aux < contador; aux++) {
            if (pLocatarios[aux].codigoLoc == codigo) {
                return 1;
            }
            break;
        }
        free(pLocatarios);
        pLocatarios = NULL;
    }
    else {
        printf("ERRO NA ALOCAÇÃO DE MEMÓRIA!");
    }
    return 0;
 }

Comment: Mostre o que já fez. Já adianto que você vai ter que guardar todos os locatários de alguma forma organizada. precisará de uma forma que você saiba onde estão todos eles, provavelmente em um *array*. Esse *array* provavelmente terá que crescer dinamicamente através de uma estrutura própria que vai alocando as partes aos poucos (como uma lista ligada) ou terá que copiar os dados para um novo *array* maior cada vez que adicionar um elemento. Ou pode otimizar isto e criar com um tamanho mínimo estabelecido e só crescer ele em momentos específicos.
Comment: Suponho que uma 'lista ligada' extrapola o conteúdo que eu posso utilizar para resolver esse exercício.
No meu primeiro teste do programa, eu pensava em após terminar o cadastro de um locatário, gravar seus dados em um arquivo, o que facilitaria a pesquisa por este código.

O resultado de um cadastro foi este => jose ? 0x01 OS=Windows_NT Path= @ÃDŽ.
Comment: Não há problema em gravar o conteúdo em arquivo mas fazer isto só para ter acesso à lista dos locatários não faz sentido e no fundo você ainda precisaria de uma solução para formar esta lista.
Comment: Vou responder mas não poderia dar uma resposta tão completa porque não vi outras partes talvez relevantes do código. Não importa tanto, só não poderei ser mais específico. Você vai ter que se virar com a informação que vou postar.
Comment: Não acho que há partes relevantes do código. Há apenas a função cadastraLocatario() solicitando os três dados, utilizando alocação dinâmica. Mas com o que você comentou acho que tenho material suficiente para pesquisar mais e tentar resolver o problema.
Comment: Poderia ajudar ver se há outros erros, porque existem vários aí no que você postou. Estou respondendo, só me dá um tempo que eu tenho algumas outras coisas que não me deixaram concluir agora, mas posto mais tarde.
Comment: É C ou C++ ? Se for C++ você pode usar Vector
Comment: @Tony Deve ser feito em C.
Answer: Aparentemente seu verificaCodigo() está no geral, no caminho certo. Tem alguns problemas no seu código como um todo que vi passando o olho:

Não entendi porque os dois parâmetros precisem ser passados como ponteiros, acredito que seja por equívoco, se não for tem mais erros porque desta forma você está acessando o endereço da memória e não os dados que deseja (daí pode estar pegando sujeira).
Não sei o que o break está fazendo ali, ele certamente não pode existir. Um break fora de um if não costuma ser útil para nada.
Pra que está havendo uma alocação de memória em uma função que só verifica algo? Ou ela verifica algo ou ela cria o novo elemento (se é que era essa a intenção). Fazer a alocação em um lugar e deixar o preenchimento em outro agrava a desorganização.
Se der erro de alocação na memória o retorno é 0 que é o mesmo retorno se ele não encontrar um código igual (duplicação), isto não faz sentido.
Aparentemente você sabe quantos locatários estão cadastrados, é isto que você recebe em contador. Se é isto mesmo, para que calcular o totalLocatarios que nem está sendo usado?
Aparentemente existem outros erros no uso de ponteiros pelas informações passadas, já que você está pegando sujeira na memória.
Tem alguns problemas em que seu código não seria confiável mas acho que não é relevante para quem está aprendendo.
Não é um problema mas não gosto dos nomes das variáveis que você usa, elas não indicam bem para que está servindo, chega indicar uma coisa e faz outra. Você chama o seu tipo da estrutura de Locatarios mas lá só cabe um locatário. O ponteiro para o array deles sim faz sentido no plural.
Como é só um exercício nem vou falar do problema de guardar um valor monetário em float.

Provavelmente a solução mais simples para o que você deseja é fazer realocações do pLocatarios toda vez que for adicionar um novo elemento. Pode não ser muito eficiente mas resolve. E assim sua função de verificação de duplicidade fará sentido. Seria algo assim:
pLocatarios = realloc(pLocatarios, (sizeof(pLocatarios) / sizeof(pLocatarios[0]) + 1) * sizeof(pLocatarios[0]);

Isto está pegando a quantidade de elementos no array, somando 1 e alocando esta quantidade vezes o tamanho de cada elemento. Você precisará fazer esta operação anates de adicionar um novo locatário.
Se você mantem a quantidade de locatários guardada em algum lugar fica um pouco mais fácil, talvez:
pLocatarios = realloc(pLocatarios, (totalLocatarios + 1) * sizeof(Locatarios);

Coloquei no GitHub para referência futura.
Esta alocação deve ser feita onde vai adicionar dados do novo locatário. Na prática é possível criar um código só com o realloc() já que se o ponteiro inicial for NULL ele age exatamente igual ao malloc.
Talvez nem fique muito ineficiente já que o sistema operacional pode, em alguns casos, fazer otimizações na alocação que evite a cópia de dados. De qualquer forma para um exercício não importa.

Problemas com alocação dinâmica


Stokes' Theorem with a sphere

Question: Use Stokes' theorem to evaluate
$$
\iint_S \operatorname{curl} F \cdot \hat{n}\, dS
$$
where $F =\langle xyz, x, e^{xy} \cos(z)\rangle$
$S$ is the hemisphere $x^2+y^2+z^2=25$ for $z ≥ 0$ oriented upward.
I know how to compute the curl of the vector field. I don't know how to get the normal. I'm a bit confused about what it is.
Once I have the dot product of the $\operatorname{curl} F$ and the normal then I can redefine the sphere in terms of $\theta$ and $\phi$ (spherical coordinates) and I can compute the integral, no?
I specifically want to complete this problem using stokes' theorem.
Comment: normal of a sphere is simple. In your case, it is $(x/5 , y/5 ,z/5 )$
Answer: What Stokes' Theorem tells you is the relation between the line integral of the vector field over its boundary $\partial S$ to the surface integral of the curl of a vector field over a smooth oriented surface $S$:
$$\oint\limits_{\partial S} \mathbf{F} \cdot d\mathbf{r} = \iint\limits_S (\nabla \times \mathbf{F}) \cdot d\mathbf{S} \tag{1}\label{1}$$
Since the prompt asks how to calculate the integral using Stokes' Theorem, you can find a good parametrization of the boundary $\partial S$ and calculate the "easier" integral of the LHS of (1).
Note that the boundary of $S$ is given by:
$$\partial S=\{(x,y,z)\in \mathbb R^3 : x^2 +y^2 =25, z=0\},$$
so a good parametrization to use for $\partial S$ could be:
$$\sigma :[0,2\pi] \subseteq \mathbb{R} \rightarrow \mathbb R^3$$ $$\sigma(\theta)=(5\cos(\theta),5\sin(\theta),0)$$
and finally the integral to calculate ends up being:
$$\begin{align}\oint\limits_{\partial S} \mathbf{F} \cdot d\mathbf{r}&= \iint\limits_S (\nabla \times \mathbf{F}) \cdot d\mathbf{S} \\ &=\int_{0}^{2\pi}(0,5\cos(\theta),e^{25\cos(\theta)\sin(\theta)})\cdot(-5\sin(\theta),5\cos(\theta),0)\, d\theta,\\&=\int_{0}^{2\pi}25\cos^2(\theta)\,d\theta\end{align}$$
and from here you can use trigonometric identities to calculate the last integral.
I hope that helps!
Answer: The OP suggests some significant gaps in his knowledge.
$\nabla \times F = \det \begin{bmatrix}\mathbf i& \mathbf j& \mathbf k\\\frac {\partial F}{\partial x}&\frac {\partial F}{\partial y}&\frac {\partial F}{\partial z}\\xyz&z&e^{xy}\cos z \end{bmatrix} = xe^{xy}\cos z\mathbf i  -(ye^{xy}cos z-xy)\mathbf j + (1-xz)\mathbf k$
$dS =(-\frac {\partial x}{\partial z},- \frac {\partial x}{\partial z}, 1)$
or $dS = \frac {(x,y,z)}{z} = (\frac {x}{\sqrt{25-(x^2 + y^2)}},\frac {y}{\sqrt{25-(x^2 + y^2)}}, 1) $
Stokes theorem:
$\oint f(x,y,z) \cdot dr = \iint \nabla \times f(x,y,z) \ dS$
This implies that if $S$ and $A$ have the same contour.
$\iint \nabla \times f(x,y,z) \ dS = \iint \nabla \times f(x,y,z) \ dA$
Let $S$ be the hemisphere $x^2 + y^2 + z^2 = 25, z \ge 0,$ And $A,$ the disk
$x^2+y^2 = 25, z= 0$
$dA = (0,0,1)$
$\iint \nabla \times f(x,y,z) \ dA = \iint (xe^{xy}\cos z, -ye^{xy}cos z+xy, 1-xz)\cdot(0,0,1) \ dA = \iint 1 \ dA = 25\pi$

Stokes' Theorem with a sphere


Rails auto update database attribute after clicking submit on a form

Question: I am using simple_form in rails to create certain events. To create a new event, you are required to login as a user. The form will ask the user to enter the event name, start date, and end date. When the user clicks the submit button, I want the form to automatically update the attribute user_id in the database.
Right now in the database, the user_id field in the events table is always set to null. However I need this attribute to be set to:
events.user_id = current_user.id
Here is my events table for more info:
Note: I manually entered the values for user_id in this database.
Question: How do I update a database attribute, after a user clicks submit? Or is there a default way of always setting the user_id when a new event is created?
Here is the code in the new.html.erb events view
<%= simple_form_for(@event) do |f| %>
  <%= f.error_notification %>

    <%= f.input :name %>
    <%= f.input :start_at %>
    <%= f.input :end_at %>

    <%= f.button :submit %>

<% end %>

Answer: In your create method in your event controller, add your
events.user_id = current_user.id

before the save.
e.g. if you create the event (in the def create method) with @event = Event.new(params[:event])
then do @link.user_id = current_user.id on the next line
You can probably do @link.user = current_user and rails will figure the id out.
Comment: Thank you! That worked. I added `@event.user_id = current_user.id` in the (`def create method`)


Remover chave antiga de known_hosts (Warning: Possible DNS Spoofing detected)

Question: Ao acessar via linha de comando em Linux/MacOS, um erro parecido como o a seguir poderá aparecer
<code>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The RSA host key for dominio.com.br
and the key for the corresponding IP address 220.127.116.11
is unknown. This could either mean that
DNS SPOOFING is happening or the IP address for the host
and its host key have changed at the same time.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
(...)
</code>
UM erro parecido também acontece ao usar uma GUI, como o Nautilus no Ubuntu, de modo que não há como navegar por uma pasta de um servidor que teve uma alteração legítima.
Como resolver isso?
Answer: Em seu terminal, digite o comando:

ssh-keygen -R dominio.com.br

Esse erro ocorre porque em algum momento no passado a máquina local acessou o servidor remoto e gravou em <code>~/.ssh/known_hosts file</code> uma assinatura de quem era o servidor remoto. Porém com essa mensagem, ele está alertando você que a máquina remota não tem mais a mesma assinatura.
Nestes casos, antes de remover, procure saber porque houve esse erro. Se sabe que a máquina remota realmente alterou, como a exemplo de ter recriado uma máquina virtual para hospedar o mesmo domínio, basta remover a assinatura anterior com o comando listado.
Saiba mais também sobre Ataque man-in-the-middle


How do a get a connection string that uses windows authenication to work without windows authenication?

Question: Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyDBName;Data Source=MyServerName
this is the connection string, it can not be changed, it is in a dll from the dark ages. we are having to use it on a server outside of our domain. we can hit the server because we set up a host entry all we need is read access is there something on the sql server that can be configured to allow this connection?
but get the following:
Message: Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection.
Source: Microsoft OLE DB Provider for SQL Server
Answer: You need to either

Configure the app to run in the context of a Windows user who has sufficient permissions to the data on the SQL Server or
Create a Windows login on the SQL Server for the user(s) whose accounts the app is running under.
Comment: i tried enabling impersonation in asp.net but got an error that the domain could not resolved.
Comment: You need to make sure that the application pool in IIS that is servicing your app is running with its identity set to that of the Windows account that has access to your db.


Is there any way to use view display format to show the data in drupal 7?

Question: I have created a custom content type "listusers" and add fields to that content type. After that i created a view page where i select display format as "Table" now my output  is like below:

can any one suggest me is there any way to achieve the view as attached in below image
Answer: You could filter the view by the designation column to group the results.
To separate the tables I would create different view blocks for each result and put them one after each other. You could use the block title for the Haryana/Ambala text and style it accordingly.
In the example bellow I have a view with 3 blocks and each of the blocks displays rooms tagged by a room category.
Comment: i am getting confused.. you told me to create the different different blocks but i need a custom fields so how can i add those fields data?
Comment: What do you need a custom field for ?
Comment: like i have a custom content type and under this i am having fields like name, designation, email etc and now you told me to create three different blocks. i am confused here if i am creating a block then how can i add the data related these fields bcoz in blocks only three fields title, description and region
Comment: and one more thing like you added the filter criteria room category = prestigious location when i am trying to add there is no option. First i select the content field location and there is an options like operator equal to


phpMailer Attachment not working

Question: this is my first post and I hope that I can get some help regarding adding an attachment field in my phpMailer contact form. I have already added an uploader [browse] bar in the html website but I don't know how to link it with the phpmailer. do I have to declare it at the package which is phpmailer.php or do something with it?
I would really appreciate some help. Below is my desperate attempt.
Snippet from the code:
<?
$body = ob_get_contents();

$to = 'firstname.lastname@example.com>';
$email = $email;
$subject = $subject;
$fromaddress = "firstname.lastname@example.com";
$fromname = "Online Contact";

require("phpmailer.php"); //<<this is the original pack

$mail = new PHPMailer();

$mail->From     = "firstname.lastname@example.com";
$mail->FromName = "My Name";
$mail->AddBCC("email@example.com","Name 1");
$mail->AddAddress( $email,"Name 2");

$mail->WordWrap = 50;
$mail->IsHTML(true);

$mail->Subject  =  $subject;
$mail->Body     =  $body;
$mail->AltBody  =  "This is the text-only body";
// attachment
$mail->AddAttachment('uploadbar', 'new_file.pdf'); // the name of my html uploader is uploadbar, clicking browse to locate a file

if(!$mail->Send()) {
    $recipient = 'email@example.com';
    $subject = 'Contact form failed';
    $content = $body;

  mail($recipient, $subject, $content, "From: firstname.lastname@example.com\r\nReply-To: $email\r\nX-Mailer: DT_formmail");
  exit;
}
?>

Answer: Had the same problem, try this
$mail->AddAttachment($_SERVER['DOCUMENT_ROOT'].'/file-name.pdf');

Answer: First, make sure your upload form has enctype='multipart/form-data' as in <form method=post action=file.php enctype='multipart/form-data'>.
then, use this code in your phpmailer handler file
foreach(array_keys($_FILES['files']['name']) as $key) {
   $source = $_FILES['files']['tmp_name'][$key];
   $filename = $_FILES['files']['name'][$key];

   $mail->AddAttachment($source, $filename);
}

Comment: I replaced my AddAttachment line with all your lines. I still don't get any attachments in the email.
Comment: here is the phpmailer.php which I did not include any of its code - http://www.2shared.com/file/RcD8xdI1/phpmailer.html - What's included in my first post is the process.php
Comment: in your specific case, if upload input is named `uploadbar` use `$_FILES['uploadbar']` instead of `$_FILES['files']`
Comment: still not working. I don't know if you need more information to help you or files? Thank you by the way!
Answer: Make sure attachment file name should not contain any special character and check the file path also correct.

eg: [file name.pdf] Should be like [filename.pdf]

phpMailer Attachment not working


Proving $(T * S )(x-a)=T * S (x-a)= T (x-a)* S $ where $ S,T \in \mathcal{D'}(\mathbb{R})$

Question: Considering the definition of convolution:
If $T,S \in \mathcal{D'(\mathbb{R})} $ and at least one of them has compact support,   $\forall \varphi \in \mathcal{D}(\mathbb{R})$ $$\langle T*S, \varphi\rangle= \langle T(y), \langle S(x), \varphi(x+y)\rangle \rangle   $$
and the translation property: $$\langle T(y-a), \varphi\rangle = \langle T(y),\varphi(y+a) \rangle $$
I am trying to prove the following property:

$$(T * S )(x-a)=T * S (x-a)= T (x-a)* S $$  where $S, T$ are
distributions: $( S,T \in \mathcal{D'}(\mathbb{R}))$

My try:
I take a test function $\varphi \in \mathcal{D}$
Using the property of translation:
$$\langle (T*S)(y-a), \varphi\rangle =\langle (T*S)(y), \varphi(y+a) \rangle .....(1)  $$
calling $\varphi(y+a)=\psi(y)$:
$$=\langle (T*S)(y), \psi(y) \rangle$$
and by definition of convolution of distributions:
$$= \langle T(y), \langle S(x), \psi(x+y)\rangle \rangle   $$
$$= \langle T(y), \langle S(x), \varphi(x+y+a)\rangle \rangle   $$
using translation again:
$$= \langle T(y), \langle S(x-a), \varphi(x+y)\rangle \rangle   .....(2)$$
and now I wish I could call this $T * S (x-a)  $, but for that I guess I would instead need to have $= \langle T(y), \langle S(x-a), \varphi(x+y-a)\rangle \rangle   $, because according to the definition of convolution, I need $\varphi$ to have as argument the sum of the arguments of the $T$ and $S$.
Is this correct?
I have the following doubts :
(1) I am not very sure if $(T*S)(y-a)$ means $T(y-a)*S(y-a)$ or if the $(y-a)$ applies  just to S , so that
$(T*S)(y-a)= T(x)*S(y-a)$. I used the second one, because according to the definition of convolution, T and S take different variables:
$$\langle T*S, \varphi\rangle= \langle T(y), \langle S(x), \psi(x+y)\rangle \rangle   $$
I am also starting with a $y$ variable, because otherwise I don't get the $x-a$ in the final step
The fact that using variables with T and S is an abuse of notation also is making it confusing, because I don't know if I am abusing correctly
(2) As I mentioned at the end of the proof can I really conclude :$T * S (x-a)  $ ?  For that I guess I would instead need to have $= \langle T(y), \langle S(x-a), \varphi(x+y-a)\rangle \rangle   $
Answer: Define the operator $\tau_a$ on $\mathcal{D}(\mathbb R)$ by $(\tau_a \varphi)(x) = \varphi(x-a)$ and on $\mathcal{D}'(\mathbb R)$ by $\langle \tau_a T, \varphi \rangle := \langle T, \tau_{-a}\varphi \rangle$.
We can then write
$$
\langle \tau_a(T*S), \varphi \rangle
= \langle T*S, \tau_{-a}\varphi \rangle
= \langle T(t), \langle S(s), (\tau_{-a}\varphi)(t+s) \rangle \rangle
= \langle T(t), \langle S, \tau_{-a-t}\varphi \rangle \rangle
= \langle T(t), \langle \tau_a S, \tau_{-t}\varphi \rangle \rangle
= \langle T(t), \langle (\tau_a S)(s), \varphi(s+t) \rangle \rangle
= \langle T*\tau_a S, \varphi \rangle,
$$
i.e. $\tau_a(T*S) = T*\tau_a S.$
Comment: Thanks, very clear, I am trying to translate back with the notation they used in my lectures, Before you applied the definition of convolution, how should $T*S$ be understood :$ T(t)*S(t),$ $T(t)*S(s) $ or  $T(s)*S(s)$ ?
Comment: $T*S$ is a function of only one variable, so possibly $T(t)*S(t)$ or $T(s)*S(s),$ *not* $T(t)*S(s).$ The best certainly is to write $(T*S)(x)$ without setting variables on the individual factors.


Solve an ODE system

Question: There is a system $\dot x = x, \dot y = x+2y$. I got this answers $x=C_1\cdot e^t$ and $y=C_1\cdot e^{2t}-x/2-1/4$ but I find it wrong somehow. Will you explain the full solution to that?
Answer: Your answer for $x$ is right. Then you are left with solving $\dot{y} = C_1 e^t + 2y$. There are various ways to do it (the variation of constants formula, multiplying by an exponential factor...)
Do you know any of those methods?
Answer: $$\dot x = x, \\ \dot y = x+2y$$
I got this:
$$ x'=x \implies x=c_1e^t$$
And:
$$y' = x+2y$$
$$y' = c_1e^t+2y$$
$$y'-2y=c_1e^t$$
$$(ye^{-2t})'=c_1e^{-t}$$
Integrate both sides:
$$ye^{-2t}=-c_1e^{-t}+c_2$$
$$y=-{c_1}e^t+c_2e^{2t}$$
It's hard to tell you what mistakes you made without posting your full attempt.

Solve an ODE system