This code generates a segfault. Where have I gone wrong?

Question: The goal of this code is to quickly read some data into memory from fields in a tab delimited file and sort them.  I have found that when I run this code, I get a segmentation fault.  I assume it's something to do with my limited knowledge of strtok.  I know it would be easier to use some c++ functions for tokenizing strings, however, I would like to have this code run as fast as possible.  It seems like most c++ code would have me unnecessarily allocating space for new objects.  Ideally, the code will be run on files containing 100's of millions of lines. So, it needs to be fast.
    #include <stdlib.h>
    #include <stdio.h>

    #include <string>
    #include <iostream>
    #include <vector>
    #include <algorithm>

    using namespace std;

    class Node
    {
      public:
      string name;
      int position1;
      int position2;
      string desc;
      float value;

      bool operator<(const Node& T) const;
    };

    bool Node::operator<(const Node &T) const
    {
      int result;
      result = name.compare(T.name);
      if (result !=0) return(result);

      if (position1 != T.position1) return(position1 < T.position1);

      if (position2 != T.position2) return(position2 < T.position2);

      return(false);

    }

    class NodeList
    {
      public:
      vector<Node> nodes;
    };

    int main(void)
    {
      string filename = "table.txt";
      FILE* infile = fopen(filename.c_str(), "r");

      int buflen = 1000;
      char buffer[buflen];

      NodeList K;
      Node T;

      while(fgets(buffer,buflen,infile) != NULL)
      {
         cout<< buffer << endl;

         T.name      = string(strtok(buffer, "\t\n"));
         T.position1 = atoi  (strtok(NULL  , "\t\n"));
         T.position2 = atoi  (strtok(NULL  , "\t\n"));
         T.desc      = string(strtok(NULL  , "\t\n"));
         T.value = atof  (strtok(NULL  , "\t\n"));

         K.nodes.push_back(T);
      }

      sort(K.nodes.begin(),K.nodes.end());

      return(0);

}

EDIT: The segfault occurs in the sort command. Without the sort command the code runs normally. Edited to take comments into account. Here is the output from the debugger:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xffffffffffffffe8 0x00007fff83a078bb in std::string::compare ()
(gdb) bt
#0  0x00007fff83a078bb in std::string::compare ()
#1  0x0000000100001333 in Node::operator< (this=0x7fff5fbfeef0, T=@0x1001fffe0) at test.cpp:27
#2  0x000000010000274e in std::__unguarded_linear_insert<__gnu_cxx::__normal_iterator<Node*, std::vector<Node, std::allocator<Node> > >, Node> (__last={_M_current = 0x100200000}, __val=@0x7fff5fbfeef0) at stl_algo.h:2309
#3  0x0000000100003f28 in std::__unguarded_insertion_sort<__gnu_cxx::__normal_iterator<Node*, std::vector<Node, std::allocator<Node> > > > (__first={_M_current = 0x100200200}, __last={_M_current = 0x1002581e0}) at stl_algo.h:2406
#4  0x000000010000437b in std::__final_insertion_sort<__gnu_cxx::__normal_iterator<Node*, std::vector<Node, std::allocator<Node> > > > (__first={_M_current = 0x100200000}, __last={_M_current = 0x1002581e0}) at stl_algo.h:2439
#5  0x0000000100004422 in std::sort<__gnu_cxx::__normal_iterator<Node*, std::vector<Node, std::allocator<Node> > > > (__first={_M_current = 0x100200000}, __last={_M_current = 0x1002581e0}) at stl_algo.h:2831
#6  0x00000001000019e8 in main () at test.cpp:76

If I go up one level and look at the values, I get this:
(gdb) print T
$1 = (const Node &) @0x1001fffe0: {
  name = {
    _M_dataplus = {
      <std::allocator<char>> = {
        <__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>},
      members of std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Alloc_hider:
      _M_p = 0x0
    }
  },
  position1 = 0,
  position2 = 0,
  desc = {
    _M_dataplus = {
      <std::allocator<char>> = {
        <__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>},
      members of std::basic_string<char,std::char_traits<char>,std::allocator<char> >::_Alloc_hider:
      _M_p = 0x0
    }
  },
  value = 0
}

The values for this.name etc look like they come from the file, but whatever it is being compared to has values that are all 0's or NULL.
Comment: Get it right first; then measure whether it is fast enough.  Premature optimization is the root of much computing evil (and no, that isn't original to me).
Comment: -1 for poor research effort - please use a debugger.
Comment: How would you guarantee that each line you read would contain enough tabs? If it doesn't the first token would be split at \n i.e. newline and latter calls to strtok would return null. If you are certain each field of yours is separated by a tab, then don't use \n as an alternate except for the last call. Better yet, i believe you should use space as a separator
Comment: Also at least limit the scope of your segfault. For e.g. comment out the sort call and first only ensure if your seg fault is with in the tokenizer code. Debugger should have easily gotten you that.
Comment: You assign two different values to `T.position2`, one an `int` and the other a `double`.  It won't cause a crash, but it is unlikely to be correct. Ditto with `T.name` (two assignments, but both are strings, this time).
Comment: I did use a debugger actually. gdb. I was having trouble interpreting the STL related names. I know that it's the sort command that causes the segfault, although I'm assuming I must have corrupted something earlier.
Comment: As a matter of "correctness," consider using proper C++: `fstream`s, namely.
Answer: Compiling with g++ -Wall -g, I see that you need to include string.h to get strtok, and your operator< needs to return something if none of the earlier if statements were true. After that...

You aren't checking the return value of fopen, so the first segfault I found was when I hadn't created a table.txt to test with.
You aren't checking the return value of strtok either, so if no matching column exists, then you can pass NULL to atoi, and get a segfault there.

You need to use gdb's bt command when your program crashes to find out what line triggered the crash.
Comment: @HenryB.: It's not enough just ensuring that operator< always returns something - it must return a consistent ordering for the elements. Right now, you're returning `true` whenever compare indicates the `name` strings are different, regardless of whether the difference is a less-than or greater-than relationship. That's totally wrong. Please study a few example implementations of `operator<`.
Comment: I made the modifications you suggested.  There is still a segfault. It happens in the sort function.  (My less than operator always returrns something now.)
Comment: Look at the backtrace you got: either `this.name` or `T.name` is invalid, and is causing the call to `name.compare(T.name)` to crash.
Comment: @Jamey Sharp: Where would that come from? When I run through all the nodes in the vector, I only see the values from the file.
Comment: Hmmm. For that question, I have no answer.
Comment: @TonyD: Yeah. You were right. I needed to write: if (name.compare(T.name)) return(name < T.name);  No segmentation fault after that alteration.  I think I just had a bit of a senior moment in terms of how compare works.


SMTP Client 5.5.1 issue

Question: I have a simple web smtpclient application using C#.
<code>//store server name
string ServerName = "smtp.gmail.com";

// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient(ServerName);
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Port = 587;
MailAddress from = new MailAddress("youremailid",
    "nameprefix " + (char)0xD8 + " namesuffix",
System.Text.Encoding.UTF8);
// Set destinations for the e-mail message.
MailAddress to = new MailAddress("receipentemailid");
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// Set the method that is called back when the send operation ends.
client.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
// The userState can be any object that allows your callback
// method to identify this send operation.
// For this example, the userToken is a string constant.
string userState = "test message1";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
// If the user canceled the send, and mail hasn't been sent yet,
// then cancel the pending operation.
if (answer.StartsWith("c") && mailSent == false)
{
    client.SendAsyncCancel();
}
// Clean up.
message.Dispose();
Console.WriteLine("Goodbye.");
</code>
It's giving me:

[testMessage1] System.Net.Mail.SmtpException:the SMTP server requires
  a secure connection or the client was not authenticated.the server
  response was: 5.5.1 Authentication required .

1)- Any way to get rid of this issue?
2)- is there any restriction to keep the receipent same domain server as sender?
    i.e. both should be either of gmail.com or yahoo.com
Comment: Do you need a username and password inorder to logon to the SMTP server?
Comment: Check the documentation from gmail.
Comment: How should i know this ? @YuvalItzchakov
Answer: You have to set the credentials:
<code>client.Credentials = new NetworkCredential("username", "password");
</code>
Comment: I missed that. Are the credentials right? Also, did you place it after setting UseDefaultCredentials?
Comment: The server 'smtp.gmail.com' is already hardcoded and passed to 'SmtpClient client = new SmtpClient(ServerName)' im above code
Comment: yes ,i used : 'client.UseDefaultCredentials=false;
            client.Credentials = new NetworkCredential("2014j.....", "*******");
Comment: Honestly, I have no idea. Will do some tests later.
Comment: It's running smooth now but i didn't see any email inboxed therein (("receipentemailid")).

SMTP Client 5.5.1 issue


Benefits/Drawbacks of storing data in data structures, rather than embedding them in if/switch statements

Question: For Example, suppose I wanted to enumerate a list of strings { "ALPHA", "BETA", "GAMMA", "OMEGA" }. Two ways I can think of doing this:
<code>--- Method 1 ---
string getType(int a)
{
   switch(a)
   {
      case 0: return "ALPHA";
      case 1: return "BETA";
      case 2: return "GAMMA";
      case 3: return "OMEGA";
   }
}
</code>
Or I could create an array of strings and use it to return the corresponding string element:
<code>--- Method 2 ---
string data[] = { "ALPHA", "BETA", "GAMMA", "OMEGA" };
string getType(int a)
{
     return data[a];
}
</code>
(Assuming for a very large data set) How does the compiler deal with these two methods? What does the final assembly code look like? Is one method faster at retrieving elements than the other? Does one take more space in memory? Or do they get translated to the same machine code?
My best guess would be that method 2 works faster but also takes up more space in memory, as it needs the space for the array; whereas method 1 takes more time every time getType(..) is called but requires less memory as the variables are only stored in the assembly commands. But I still don't know how C++ or other language compilers would deal with the code, could produce something completely different.
Comment: You could probably answer some of these questions by just compiling and taking a look at the result...
Comment: Indeed, why so many people are unable to stop guessing and start looking?
Answer: Just use the array.  It's clearly more efficient for large numbers of strings, and for small numbers of strings, the overhead of using an array over a switch statement is trivial anyway.  The benefit of you learning not to do crazy things is worth the extra overhead. :-)
If you really wanted to analyze the difference, I think you'd find that it can depend on the resources of the machine you are running it on anyway, since one approach is clearly more memory intensive and the other more CPU.


Amazon CloudFormation: How to get an ELB's private IP for a specific subnet?

Question: TL;DR - Is it possible for a CloudFormation template to insert the subnet-specific internal IP address of a specific ELB into the UserData of an instance within that subnet?

We have a fleet of EC2 web servers in an Amazon VPC with six subnets, one private and one public across each of the three AZ's within EU-West-1. All servers are configured with CloudFormation.
We would like to configure Apache's mod_rpaf to log the X-Forwarded-For header (we can change the LogFormat, but this doesn't translate easily to PHP or Apache error logs; RPAF is the neatest solution for us).
As far as I know, the way an ELB is architected means that it has a 'foot' in each of its configured AZs, and this can change if the ELB is torn down or re-created.
It seems that the version of mod_rpaf in Ubuntu 12.04's repositories hasn't been updated to allow CIDR notation for the ProxyIPS directive, and in theory the ELB's IP address can be anything within our three public subnets.
The one remaining solution is to configure the module via Puppet, using hieradata generated by the instance's UserData. I know that to some degree you can interpolate references and variables within CloudFormation templates, but I'm unsure if it's possible to effectively say "Give me the private IP address for this ELB in this subnet".
Answer: We had same problem, below command I use for getting internal IP of ELB "LAMP-Prod"
aws ec2 describe-network-interfaces --filters "Name=description,Values=ELB LAMP-Prod" |grep -wE 'Description|PrivateIpAddress'

Or using JQ and without the need to specify an ELB name
 aws ec2 describe-network-interfaces --filters Name=requester-id,Values='amazon-elb' | jq -r '.NetworkInterfaces[].PrivateIpAddresses[].PrivateIpAddress'

Comment: Except it helped me, who searched Google for "ELB private IP".
Comment: The original author downvoted this solution for not being 100% compatible with his 'requirements'...Then chose a solution which mentions scrapping logs files...go figure...
Comment: @Froyke - just seen this, ultimately I didn't mark the answer as accepted due to the log-scraping comment - I accepted the answer due to the first two words, which give the correct answer to my original question, which was centred specifically around CloudFormation.
Comment: Not a solution. I was looking for CloudFormation. Downvoted.
Answer: If you want to get the private ip address of an elb, check network interfaces under network and security in you ec2 dashboard.
Comment: He is actually correct, if you goto network interfaces, you can see all your network interfaces.  If you query for your ELB name, it will filter out everything but the interfaces that you have on that ELB, and then you can drill down.  Not programatic, but works.
Comment: This is accurate and deserves more upticks.
Comment: no. IPs for ELBs doesn't stay static. they change very frequently. you can observe it by just pinging the elb endpoint
Comment: Thanks for the hint. Does it remain static?
Answer: JQ parsing version, just FYI.
aws ec2 describe-network-interfaces --filters "Name=description,Values=ELB your-elb-name" --output json | jq ".NetworkInterfaces[].PrivateIpAddresses[].PrivateIpAddress"

Answer: Unfortunately not.  I've gone back and forth with our AWS solutions engineer on this and currently there's no way to query the internal IPs for an ELB.  I'm currently scraping log files to find them.


How does the RB know when to grasp the ball on a read option and when the QB is selling the fake?

Question: In American football, on read-option plays, how does the RB know when to fully grasp the ball and when not to because the QB "pulls" the ball?
Commentators praise the QB on plays where he sticks the ball in the belly of the RB, only to pull the ball at the very last second and keeps it for a huge gain.  In slow motion, it really looks like the ball is in the stomach of the RB with the RB's hands almost around the ball when the QB pulls it.
They have also blamed the QB/RB when there's a fumble because of miscommunication due to:

the QB deciding to handoff the ball but the RB doesn't grasp the
ball and it gets fumbled away or
the QB tries to pull the ball but
the RB has already fully grasped the ball and the ball gets knocked/pulled out by the QB and is fumbled.

I know teams who run a read-option offense probably practice these plays a lot so they "know", but as a layman, I'd like to know how the RB "knows" what the QB is going to do.  Does the QB bark some code word before handing/keeping the ball or they both "know" because they both read the DE and know what the other is going to do and the fumbles are just unfortunate mistakes?
Answer: The other answer isn't wrong but it really doesn't cover the read option exchange.   It isn't that complicated and I just coached (the youngest team I have ever coached) a group of 2nd graders that ran the read option very very successfully.   Here is what the play comes down to.

Unlike most run plays, this hand-off includes very little movement from the RB.   He may be moving forward but it is slowly.   On most run plays the RB would be expected to explode through the hand-off.
The QB should commit a push of the ball into the stomach of the RB.   Not "Drop the ball".   When the QB and RB are on the same page they will be comfortable in the read timing where the RB will hold.   Sorry I have never put a stop watch to this but it is less than a second and a couple of 2nd grade RBs had it down in the QB really had it.   So during that read phase of the play the RB will be in an athletic stance with arms spread to receive hand-off.   He will instantly move forward with the ball on push.   With no push he will rely on the practiced read timing or he will move instantly as QB disengages the ball.   Note that there can be a push and a pull.   If the QB really wants to sell it they can push which will cause the RB to start their sprint and grab... But it is the QB's job to make sure they secure the ball back ASAP (and a little bit of the RBs job to not wrestle for the ball or stop running).

So as a coach there is technique (QB looking at right spot, QB turned right, RB turned right, RB forward slant but not running), there is read time (some refer to as the mesh), and then there is the execution of the push or disengage.
I would like to add that a true read option is having an unblocked man at the line of scrimmage.   The QB is attacking the movement of that person which allows the offense to play 10 vs 10 - usually at least one offensive player is negated (the QB) so the defense always is one player up.
However...
Since the read went to the NFL, NFL coaches learned (albeit painfully slow) that the QB is a runner in that play and not a QB by rules.   Meaning that if a QB runs a read option they are fair game to get whacked even if they don't have the ball - if they even give the smallest fake.   So the NFL coaches (I could give you the exact game it changed) reviewed with the referees and made sure their "readed defensive player" could just lay out the QB.   (the end of the Colin era)
Well this quickly trickled to college/high-school/peewee level.   And I had a son that was a very small D1 DE/DT and if you ever ran the read against him you might as well get the trainers on the field for the QB.   RB got 7 yards, well that's OK because QB is gone.   Just standing there doing a fake and BOOM.   I can't remember how many times in games he would just kill the QB, the ref would come over and say take it easy, he then asked the ref if it was illegal, ref said no, and boom QB nailed on the next read option - honestly I can't ever remember a team running the read option vs him more than twice.
And...  why I mention this.
Most read option plays aren't really read options.   They are a RB/QB fake mesh which looks exactly like a read option except that the QB is no longer reading an unblocked player... which means it is really just an option.    But we call it a read option because it is a QB in pistol or shotgun with a mesh/read with a RB that looks just like a read option.    There are a few teams that run the true read option but this is few and far between as they don't want to risk QB injury or fumble.   Most "read option" plays are normal blocking and QB just doing what he wants based on defensive alignments and stunts.
Answer: According to NFLBREAKDOWNS,

Unlike most running plays, he does not immediately grab the ball; he keeps his arms open, ready to have the ball taken away.

The quarterback will pull the ball while the running back has his arms open. If the quarterback realizes he does not want to pull the ball, he will let go. If he lets go, the ball will fall into the running back's hands, and the running back will secure the ball. If it gets very late and the quarterback (who is responsible for "reading" the defense) has not made a decision, fumbles are more likely to occur. When a quarterback pulls the ball very late, it is usually because he has not read the defense quickly and not by design.


DIferença de lang e meta charset em html

Question: Estou com dúvida de qual a diferença entre as definições <meta lang="pt-br"> e <meta charset="utf-8">.
Comment: Lang é somente para especificar para BOTs e afins qual o idioma provavel do site, ou seja é para facilitar, já charset é para definir a codificação que a págian usa, tipo iso-8859-1 ou utf-8 (existem outras). Ambas não tem relação alguma.
Comment: Charset é tipo uma abreviação de "character set" ou seja, "conjunto de caracteres" o UTF8 engloba um grupo imenso de Characteres https://en.wikipedia.org/wiki/UTF-8 caracteres que pode ser usados em Inglês, Espanhol, PT-br :) etc..
Answer: Ambos atributos não tem relação alguma, cada um tem um objetivo.
O atributo lang= é somente para especificar para BOTs e afins qual o idioma provavel da página ou de um elemento HTML especifico, por exemplo na mesma página:

olá mundo

Hello world

olá mundo

Hello world

Indica aos bots e afins que o primeiro
 esta em português e o segundo em inglês, ou seja é para facilitar a vida dos BOTs (ou qualquer outro tipo de software cliente).
É claro que se definir na tag  para informar que a página toda esta em determinado idioma.
Já o atributo charset= usado na tag <meta>, assim:
<meta charset="(codificação escolhida)">

ou a meta-tag:
<meta http-equiv="Content-Type" content="text/html; charset=(codificação escolhida)">

Servem para definir a codificação que a página usa, tipo iso-8859-1 ou utf-8 (existem outras), o tipo de codificação não tem relação com idioma, mas sim com o sistema de carácteres que irá usar, e este mesmo sistema de caracteres pode ser usado por inúmeros idiomas, como é o caso do utf-8, note que o charset vai definir a página toda, ou seja você não pode usar dois charsets na mesma página, como expliquei nesta resposta:

Dúvida com charset=iso-8859-1 e utf8
Answer:
Meta tag content-language: ela é a responsável por identificar em qual idioma está escrito seu site. Geralmente, a identificação é feita por abreviações dos principais idiomas. Exemplo: en-us (inglês norte-americano); pt-br (português brasileiro).
já A tag meta charset="UTF-8" é uma tag meta utilizada para comunicar aos navegadores qual é o formato de codificação de caracteres utilizado naquele documento.
Em outras palavras, essa tag serve para que os navegadores saibam como devem renderizar os textos incluídos em uma página específica.cujo idioma contenha caracteres especiais sem a exibição de erros.
Comment: A documentação orienta a [não usar o elemento meta `content-language` para declarar o idioma do documento](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language#:~:text=Do%20not%20use%20this%20meta%20element%20like%20this%20for%20stating%20a%20document%20language) use o atributo global [lang](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang) no documento ou partes dele.
Comment: Se procurar a norma [RFC 9110 na Seção 8.5. Content-Language](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-language) verá que o cabeçalho `Content-Language` descreve a linguagem nativa da audiência pretendida pelo documento, o que não significa e nem é o mesmo que identificar a linguagem na qual o documento está escrito.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


is there a note location chart available for 22 hole chromatic harmonica?

Question: I am looking for a chart that shows the location of notes, for both draw and blow, as well as the key pressed and unpressed, for a 22 hole chromatic harmonica
Something like this but for a 22 hole chromatic
I have been searching for hours and I can find ones for diatonic and 12 hole chromatic, but not for a 22 hole one
Could anybody point me in the right direction?
Thank you
Answer: Like you, I've searched for a while for information about 22-hole chromatic harmonicas. The only 22-hole instruments I've found information about don't have different blow and draw notes for each hole. Instead, instruments such as the Unica 22-hole chromatic harmonica have two, rather than four notes, for each hole. (Usually, a chromatic harmonica has 4 notes for each hole: blow and draw notes without using the slide; and blow and draw notes using the slide.) The Unica instrument produces the same pitch when a particular hole is blown or drawn. This gives two notes per hole; one with and one without using the slide.
This website (which I gather you found, too) has charts for a wide range of different types of chromatic harmonicas. One of these is a 22-hole, 44-reed, 44-tone slide harmonica, which is of the type I mention above. Below is a picture of this instrument (showing the 22 holes) and the fingering chart for this instrument (showing just two notes for each hole - i.e. slide out and slide in):

As I say, this is the only fingering chart I've managed to find for any 22-hole chromatic harmonica. If your instrument produces the same notes for blow and draw on any particular hole, this might be the correct note location chart. If not, I'm as stumped as you are...
Comment: Ah, well if that is your main question, I would say go for the 12-hole, these are the conventional chromatic harmonicas, with conventional (blow and draw) note location. As far as I can tell, the 22 hole doesn't give you more notes; they are just cheaper because there are no air valves, as each hole only has the same pitch for blow and draw notes.
Comment: I had found this page, but that figure doesn't show which ones are blow and which ones are draw
Comment: Aha! This instrument doesn't have blow and draw notes, it only has **"one tone per one hole"**. Does your instrument have blow and draw notes for each hole?
Comment: This question perplexes me, as I have several harmonicas, mostly Hohner. However, they're about 1,000 miles away right now, so when I get home, I'll play them all and report back...  But I feel that most will produce the standard scale, with the scale a semitone out with the button pressed. Watch this space.
Comment: Cheers, Tim. As ever, you are the font of all knowledge!
Comment: I noticed that the company calls this model Unica and has only one note per hole. so does this mean this chart is for this specif manufacturer and their model? If I buy any other cheaper brand harmonica with 22 holes, how likely is it that it's note layout would be different?
Comment: I don't have a harmonica yet so I am doing this to find out whether it would be better to buy a 12 hole or 22 hole one. among the harmonicas I've found, the layout charts for 12 hole ones are more straightforward, but the harmonicas are more expensive. And I couldn't find the layout chart for 22 hole harmonica, but the price is same as the 12 hole one. So I was thinking if the 22 hole one gives me more notes, may be it would be better to but the 22 hole one.
Comment: Been a long time coming back to this question! Sorry! Come on, it's not 6 yrs yet! My Hohners are 16 hole chromatics, a couple are called '64s', as that's the number of notes available. So four octaves, and what I would call standard tuning (in C) B D B D B D D B, for C D E F G A B C in each octave, and diatonic C# with button depressed.


Is $K[x_1, x_2,...]$ normal or not?

Question: As the title speaks for itself, is the polynomial ring in infinitely many variables over a field normal or not?
Can someone provide a reference/proof? Thanks
Also, what about a directed union of normal subrings? Is that normal?
Tangential to this, what's a criterion for an element in $K[x_{1},x_{2},\ldots]$ to be nilpotent? We know that in $K[x]$ we have that $f$ is nilpotent if and only if the coefficients are nilpotent and similarly in finitely many variables. Does that hold in our case too?
Comment: Since your ring is the union of polynomial rings in finitely many variables, you should have no trouble fescribing the nilpotent elements!
Comment: Likewise for normality, really. It would be best if you told us what you did and explained where you goy stuck.
Comment: For the question about normality, as a hint note that any element of the fraction field $K(X_1,...)$ will be an element of $K(X_1,...,X_N)$ for some $N$. Similarly, any polynomial with coefficients in $K[X_1,...]$ will be a polynomial with coefficients in $K[X_1,...,X_M]$ for some $M$.
Comment: Dear @Mariano, when you write "where you goy stuck", are you blaming the OP for not being Jewish?
Answer: If $R$ is an UFD (unique factorization domain), then $R$ is integrally closed (see here). The polynomial rings in finitely many indeterminates are UFDs. Moreover, $K[X_1,\dots,X_n,\dots]$ is also an UFD (why?), so it is integrally closed.
A direct union of integrally closed rings is integrally closed.
Remark. If $K$ is a field, as I suppose to be, then $K[X_1,\dots,X_n,\dots]$ is an integral domain and its only nilpotent element is $0$. In general, if $K$ is a commutative ring, then you have the same criterion as for the polynomial rings in finitely many indeterminates.
Comment: Thank you for the answer, everything is clear; I forgot that UFDs are normal
Answer: Since the polynomial ring in finitely many variables over a field is a UFD, it is normal.
Hence it suffices to prove that a directed union of normal subrings is normal.
Let $A$ be a directed union of a family of normal subrings $(A_i)_{i \in I}$.
Since every $A_i$ is an integral domain, $A$ is also an integral domain.
Let $K$ be the field of fractions of $A$.
Suppose $\alpha \in K$ is integral over $A$.
There exists $c_1, \cdots, c_n \in A$ such that $\alpha^n + c_1\alpha^{n-1} + \cdots + c_n = 0$.
$\alpha$ can be wriiten as $\alpha = \frac{a}{b}$, where $a, b \in A$.
Since $(A_i)_{i\in I}$ is directed, there exists $i \in I$ such that $a, b, c_1,\dots,c_n \in A_i$.
Hence $\alpha$ is contained in the field of fractions of $A_i$ and it is integral over $A_i$.
Since $A_i$ is normal, $\alpha \in A_i$.
Hence $A$ is normal.

Is $K[x_1, x_2,...]$ normal or not?


What will happen if a custom module has the same name as a contrib module?

Question: What are the consequences of two modules sharing the same machine name?
For instance, if I write a custom module named 'views' and do not have the contrib module 'views' enabled, will the update manager attempt to update my custom module according to the contrib project status?
Answer:
I write a custom module named 'views' and do not have the contrib module 'views' enabled, will the update manager attempt to update my custom module according to the contrib project status?

No it won't. The update manager looks at the packaging information added to the .info file for released modules, as long as your module doesn't have that data in the .info file (no reason why it would), then you won't have any problems.
The other answers are of course correct insofar as you can't have both modules enabled at the same time. You'd never even get to the point of seeing the fatal errors though, Drupal simply wouldn't let you install a module that has the same machine name as another module that's already installed.
You should aim to name your modules differently than the most popular module in existence, though, if only to save the sanity of the poor developer who eventually takes over the project from you.
Answer: It will most likely end up in fatal PHP errors.
If you implement a hook that the contrib module also implements you will get a
<code>: Cannot redeclare hook() (previously declared in contrib_module.module)
</code>
Also, your Drupal website will only pick up one of the two modules.
So in short: you have to avoid using the same modules (or theme) names. It will totally mess up your Drupal installation
Comment: Drupal wouldn't even let you get that far (two modules with the same machine name enabled), you'd have to mess with the system table manually to make that happen
Answer: The second one will not work. You can't have two modules with the same name enabled at the same time.
Comment: I agree with this. That's why there is a namespace. Just like you can't have two files with the same name.
Comment: The OP is not asking about two enabled modules with the same machine name, or even two modules with the same machine name copied in the module directory.


Find the maximum of $\frac{1}{1+|x|}+\frac{1}{1+|x-a|}$

Question: Let $a>0$. Show that the maximum value of the function
$$f(x)= \frac{1}{1+|x|}+\frac{1}{1+|x-a|}$$
is $$\frac{2+a}{1+a}.$$
really need some help with this thing
Answer: Study what happens in each of the three regions $\{x<0\}$, $\{0\le x\le a\}$ and $\{x>a\}$.
Answer: $f(a) = \dfrac{2+a}{1+a}$, and $f(x) = f(a-x)$, it suffices to consider $f$ on $[0,\frac{a}{2}]$, and on this interval $f(x) = \dfrac{1}{1+x} + \dfrac{1}{1+a-x}$, and $f'(x) = -\dfrac{1}{(1+x)^2} + \dfrac{1}{(1+a-x)^2} \leq 0$, thus $f(x) \leq f(0) = \dfrac{2+a}{1+a}$.
Answer: The function $\color{green}{\frac1{1+|x|}}$ is even and decreases from an angular point at the origin.  $\color{magenta}{\frac1{1+|x-a|}}$ is the same function, shifted by $a$.
The $\color{blue}{\text{sum}}$ has two symmetric maxima, at the angular points $x=0$ and $x=a$, where the function equals $\frac1{1+0}+\frac1{1+a}$.

For complete rigor, one must show that the derivative changes sign at the angular points, which is always true: $f'(0)=\pm\frac1{(1+0)^2}-\frac1{(1+a)^2}$.
Answer: Hint: Find the derivative of $f$ using the fact that
$$
\frac{\partial}{\partial x}|x|=\frac{x}{|x|}.
$$
Then find out where $\frac{\partial f}{\partial x}=0$, or just try to find out what is happening for the derivative when $x=\frac{2+a}{1+a}$.


Why am I getting a nullPointerException in Java?

Question: The exception doesn't come up until I click on the startGame button.  I get the error saying Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at helloworld.HelloWorld$3.handle(HelloWorld.java:123) I have no idea what that error means.  The error happens on the line players.add(new Player(0, "Amrit"));What am I doing wrong?
public String gameStatus = "Pending";
public ArrayList<Player> players;

    startGame.addEventHandler(MouseEvent.MOUSE_CLICKED,
        new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent e) {

                gameStatus = "Started";
                players.add(new Player(0, "Amrit"));
                players.add(new Player(1, "Tyler"));
                players.add(new Player(2, "Scott"));
                players.add(new Player(3, "Ryker"));

                while(gameStatus == "Started"){

                    //Select first two settlements with one road extending from each
                    for(int s = 0; s < 1; s++){

                        for(int p = 0; p < players.size(); p++){

                            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                            alert.setTitle(players.get(p).name);
                            alert.setContentText(players.get(p).name + ", please select your first settlement and place a road next to it.");

                        }
                    }

                    gameStatus = "Ended";
                }

            }
    });

}

Here is Player.java:
package helloworld;

import java.awt.Point;
import java.util.ArrayList;

public class Player {

    public int ID;
    public String name;
    public ArrayList<String> hand = new ArrayList<String>();
    public int points;
    public Point[] citiesBuilt;
    public Point[] settlementsBuilt;
    public int citiesAvail;
    public int settlementsAvail;
    public Point[] roadsBuilt;
    public int roadsAvail;

    Player(int id, String playerName){

        ID = id;
        name = playerName;

    }
}

Comment: `players` is null. You can't add elements to a list that doesn't exist.
Answer: players is not initialised, when you try to use it is null. Change that piece of code in:
public ArrayList<Player> players = new ArrayList<>();


Bug in chrome after photo upload

Question: Link http://invait.ru/CollectiveGift_template1.php
Browser is Chrome
I do the following:
1) Go on link http://invait.ru/CollectiveGift_template1.php
2) Choose an image

3) When showing an image for crop, i click on it without a crop area

And now my page scrolls down.
Tell me please how stop this bug in chrome?
Code JSCROP HERE
P.S.: Firefox doesn't have this bug...
P.P.S.: please if you want click on downvote tell mme answer. I think aboout this problem 2 days...
Comment: Is this your website ? If so.. do you know which function is triggered when clicking ?
Comment: when click on image work `Jcrop.js` about this - https://github.com/tapmodo/Jcrop
Comment: when i click outside the crop area it fire this error:
Uncaught SyntaxError: Unexpected token . jquery.Jcrop.css:11
hope this help
Comment: Doesn't seem to belong anywhere on stackexchange
Answer: Find this part of your code in your Jscrop.js:
<code>  function watchKeys() //{{{
  {
    if (options.keySupport) {
      $keymgr.show();
      $keymgr.focus();
    }
  }
  //}}}
</code>
And remove this line:
<code>      $keymgr.focus();
</code>
It is found on line 1238 in your file. Tell me if this fixes things.
This will remove the keys functionality.
Please take a look at this discussion: http://code.google.com/p/jcrop/issues/detail?id=39#c4
If you need the keys functionality, try changing fixed to absolute on line 1224:
<code>var $keymgr = $('<input type="radio" />').css({
        position: 'fixed'
</code>
and roll back the previous change
Comment: You can't give any kind of meaningful answer to a meaningless question
Comment: @GordonM if you think that question is meaningless said me answer please
Comment: code jscrop [**here**](http://pastebin.com/npUVq4Ze)
Comment: Try the update - remove that line
Comment: @DreamWave Big thanks, worked))
Comment: There should be a problem now with the key events. There is another fix to this problem if you need that resolved too. Please take alook at this discussion: http://code.google.com/p/jcrop/issues/detail?id=39#c4

Bug in chrome after photo upload


Pipe and Tap VS subscribe with ngxs

Question: I am playing around with pipe and subscribe. If I am using pipe with tap, nothing will log in console. If I am using subscribe, it's working. So what I am doing wrong?
import { Observable } from 'rxjs';
import { tap, take } from 'rxjs/operators';

this.store.select(state => state.auth.authUser).pipe(
  take(1),
  tap((data) => {
    //Not Working - no console output
    console.log('[Tap] User Data', data);

  })
);

this.store.select(state => state.auth.authUser).subscribe((data) => {
  // Working - user data output in console
  console.log('[Subscribe] User Data', data);
})

I am using RxJs 6, TypeScript and ngxs as store in Angular 6.
Answer: My answer is in two parts... What you asked, and what you need .
The values of an Observable only flow through the pipe operators when there is an active subscription. That is why you are seeing this behaviour. So you should do something like this:
this.store.select(state => state.auth.authUser).pipe(
  take(1),
  tap((data) => {
    console.log('[Tap] User Data', data)
  })
).subscribe();

But what it seems that you are looking for is a state snapshot. You can do this as follows:
let data = this.store.selectSnapshot(state => state.auth.authUser);
console.log('[selectSnapshot] User Data', data);

Answer: tap (or do in the old version of RxJS) -> Transparently perform actions or side-effects, such as logging (as definition already says).
But, in your case, you forgot to "subscribe()" to your Observable and that's why you don't see your "User Data" in the Console.
On the other hand, in the second case, you already subscribe to an Observable.
Answer: Got it! I have to append subscribe(). So it is:
this.store.select(state => state.auth.authUser).pipe(
  take(1),
  tap((data) => {
    console.log('[Tap] User Data', data)
  })
).subscribe();

Pipe and Tap VS subscribe with ngxs


Views, find content types with field NOT IN other content type

Question: Content Type A
-Nid A
-Field A
Content Type B
-Nid B
-Reference Nid A
How can I find in a view all As that have no reference in B ?
in sql this is
<code>select A.field
FROM TABLE A
LEFT JOIN TABLE B
ON A.KEY = B.KEY
WHERE B.key IS NULL
</code>
I have tried Views reference filter, but it is very slow and consume a lot of memory (the trick with this modules is not a join but a SELECT... NOT IN (...).
Which is very inefficient, because, i have 16.000 As and 14.000 Bs.
Is there any efficient solutions with views?
Thanks.
Answer: Well, maybe it is idiotic, but finally I understood the issue with the relationships and the "referenced vs referencing"
So, what I did was:
relationships : "Content referenCING Content from A_REFERENCE_IN_B"
Fields A (the fields you want)
Filter type = Type A
Filter NID (using the relationship) , is null.
Amazing, and super fast.
The important part is REFERENCING not referenced.
Thanks.
Comment: Thanks for coming back with your solution. I was just about to post this.


I cannot turn off cache

Question: I tried everything to turn the cache off. Even when using drushs command "cr" it does not help.
I used this guide:
https://www.drupal.org/node/2598914
I cannot work like this. I also turned on devels theme rebuild on page view feature. Although I don't understand what is meant with this here:

Rebuild the theme information like the registry
  While creating new templates, change the $theme.info.yml and theme_ overrides the theme information needs to be rebuilt.

Example:
<code>function theme_preprocess_taxonomy_term(&$variables) {
    kint("1");
}
</code>
When changing the number even "drush cr" does not help. I got to refresh like 4 times until the browser shows the change.
Its not like that with kint - also "var_dump()" needs it's 4,5 times.
Could anybody please tell me what to do?
Comment: `drush cr` clears all the caches in drupal. So assuming you did not break drush or the caching system, it could be local browser cache.
Comment: There are different types and levels of cache in Drupal 8. Can you edit your question and add which cache cannot be turned off? Or if you're not sure, can you give an example of the behavior you see, what you were expecting/hoping to see instead, and how this tells you that the cache is not properly turned off?
Answer: Browsers can be pretty aggressive about caching. Provided you're not using some other caching layers like redis/memcache, varnish, or a CDN, I'd start by disabling the browser cache.
In Firefox, open the inspector and click on the gear icon in the top right to open the Toolbox Options menu. Under the Advanced settings section, check the 'Disable HTTP Cache (when toolbox is open)'. I think Chrome is very similar in this.
Also be sure to use the hard refresh option. For Firefox it's Ctrl+f5. https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly

I cannot turn off cache


When/why should I start using a database?

Question: I'm currently in the process of evaluating the design, and possible reimplementation of an in-house app our engineers use.
Although the application handles large amounts of data. Only two sets of values (floats) are saved along with a simple name and description of the data. In my opinion the current application is in overkill territory using a normalized access database to store what evaluates to 7 fields of strings and floats.
At what point do you start looking at transitioning from a flat file or serialized XML to a relational database or vice versa?
Comment: strange; i cant mark this as community wiki...
Answer: I would recommend using a lightweight database like SQLite which reduces a lot of the overhead of using a database.
http://sqlite.org
Comment: "abstracting the db", why are kids these days so scared of SQL?
Comment: With a nice ORM abstracting the DB so he can transition to something bigger in the future if need be. Pays to design defensively.
Comment: scared? The "standard" is inconsistent, every DB software has its own flavour of SQL, its escaping is a royal pain (especially when creating stored procedures and functions), you need to encapsulate and escape data very carefully to avoid SQL injection... but hey, that's nothing to be scared of!  - It is just a reason to avoid SQL altogether if possible.
Comment: Using SQLite doesn't necessarily mean you have to use SQLite-specific SQL.  We don't have any SQLite specific SQL in our application.  The advantage though is SQLite requires no installation, no maintenance, and is really lightweight.
Answer: Databases can have huge advantages over flat files, even if you only have a single table with a few values.
They can dramatically improve query speed if you have a large amount of data - if you only need to find one value via a key, pulling this from a DB with an index prevents you from having to parse the entire file and search.
Comment: Don't forget data integrity issues too. DBs take care of dealing with making sure the data actually gets written to disk.
Answer: You should use the db right away because of a key word: engineer s (the plural is key)
Trying to recreate the ACID principles of any worthwhile RDBMS, even for a small amount of data even for a few users, will clobber your chances for success. You also won't have backups, custom querying and a dozen of other abilities that an RDBMS provides "out of the box."
Answer: Databases are going to be better equipped to query the data. If you mean 7 values - use a flat file. If you mean 7 fields, where there could be hundreds or thousands of records (each containing 7 fields), then use a database - particularly if you need to sort or otherwise query those records.
Answer: I start when I have to maintain a large set of related data entities.
When you a start having many-to-many or many-to-one type relationships within your data, it is time to think about using a relational database to maintain relational integrity.


Push a notification from Android app to Gear 2 (Tizen)?

Question: I can't seem to find a document on how to push to Gear2 from my Android app. The closest I can find is this tutorial on building the Integrated app, but it's a fetching scheme (data only transferred when the user presses a button on the watch) http://developer.samsung.com/events/developer-blog/blog/Tutorial-How-to-build-a-Basic-Integrated-Gear-Application
So I'm wondering is the push is done via standard Android Wearable Notification, like here ? http://developer.android.com/training/wearables/notifications/creating.html
or any pointer to documents?
Thanks.
Answer: http://img-developer.samsung.com/contents/cmm/SamsungGearApplication_UIDesignGuideline_1.0.pdf.
section 3.4
Notifications app section.
I don't think any code is necessary (though I haven't tested this myself)
The default behaviour is to push all notifications, but it can be controlled using Gear Manager App.


Calculating Birthday Problem probabibilites for different number

Question: A fellow programmer I know is designing his system around a random ID per "active" user, however this ID only has 1 million different possibilities. Thinking of the Birthday Problem I thought to myself that this isn't very safe even with a small userbase at first.
I was wondering how I could calculate for a set of different possibilities (1 million in my case) how many users you could use before you get a percentage chance of collision? I have tried solving this programatically and I came up with about an average of 1250 users where the most collisions started appearing. I found some formulaes but they all seem to use giant factorials that my programs / calculators can't perform.
Is there any way to solve this with a single equation (instead of recursion), something like:
With x different unique ID's, you'd expect a y% chance of a collision at n users. (x and y being input)
Sorry if I'm using the wrong definitions, just a programmer with enthusiasm for math :)
Answer: The Wikipedia article says the number needed for $50\%$ chance of collision where there are $n$ possible days is about $\sqrt {2 \ln 2 n}$.  That has no large factorials in it.  It is about $1177$  To deal with large factorials, the standard approach is Stirling's approximation $n! \approx (\frac ne)^n\sqrt {2 \pi n}$  It is quite accurate and if you take logs you avoid the big numbers.
Comment: So are these just for 50% or is it possible to get different percentages with the sqrt(2ln2n)?
Comment: You can adapt the $2 \ln2$ constant to give the percentage chance you want.  If you follow the article they put in $\frac 12$ on the left because they want the $50\%$ chance.  Plug in your favorite number and follow through.
Comment: Accepting this as an answer. So for example if I wanted to test for 33% chance I'd do sqrt($3ln3n$)? EDIT: Or do you mean 1/2 because squareroot is the same as to the power of 1/2 so ($2ln2n$)^1/3?
Comment: Ignore my previous comments, I understand now :)


Non injective continuous maps

Question: Motivated by comments on this question  we ask the following question:
Let $f:M\to M$  be  a  continuous map where $M$ is  a  compact  manifold and $f$ is not injective. Are there necessarily infinite number of pairs $(a,b)$ such that $f(a)=f(b)$?
What about if we replace "compact  manifold" with closed unit ball in $\mathbb{R}^{n}$ or  a compact manifold with boundary?
Answer: Yes, if $f$ is not injective, there are always infinitely many such pairs - if the dimension of $M$ is $> 0$, for $\dim M = 0$ there are only finitely many such pairs since a compact manifold of dimension $0$ is finite. Let $a,b \in M$ with $f(a) = f(b)$.
If $f$ is not injective on any neighbourhood of $a$, then we find infinitely many pairs accumulating at $a$: Let $(V_n)_{n\in \mathbb{N}}$ be a neighbourhood basis of $a$ with $V_n \supset V_{n+1}$ for all $n$. By assumption, $f$ is not injective on $V_0$, so we find $a_0 \neq a,b_0 \in V_0$ with $f(a_0) = f(b_0)$. Let $n_1$ be minimal such that $a_0 \notin V_{n_1}$. Since $f$ is not injective on $V_{n_1}$, we find $a_1 \neq a, b_1 \in V_{n_1}$ with $f(a_1) = f(b_1)$. It is clear how the construction continues and yields (countably) infinitely many pairs $a_k,b_k$ with $f(a_k) = f(b_k)$. Same for $b$.
If there are disjoint open neighbourhoods $V$ of $a$ and $W$ of $b$ such that $f$ is injective on both these neighbourhoods, by the invariance of domain $f(V)$ and $f(W)$ are open neighbourhoods of $f(a) = f(b)$, so every point of $f(V) \cap f(W)$ is the image of (at least) two distinct points, so we have even $2^{\aleph_0}$ many pairs $x\neq y$ with $f(x) = f(y)$.
If $M$ is a manifold with boundary of dimension $> 1$, it is possible that there are only finitely many such pairs, consider a disk that is bent into an annulus such that there is exactly one pair of points on the boundary where the image of the boundary curve intersects.

Non injective continuous maps


OneToMany ou ManyToOne?

Question: Boa noite, eu tenho algumas dúvidas básicas de iniciante
Eu preciso criar uma linha temporal que tenha o seguinte: Quais eventos ocorreram em determinado intervalo de datas, quem nasceu e que morreu neste intervalo? Eu tenho as classes Pessoa, Evento e Timeline. Minha classe Timeline é a que determina o intervalo de datas, assim um intervalo de dados tem muitos eventos. Com essa lógica eu teria que criar uma uma classe para Nascimentos e outra para Falecimentos ou posso criar uma única para representar isso com um atributo para diferenciar e como seria ela? Como o relacionamento é OneToMany vai ser gerado as tabelas Timeline_Evento, Timeline_Nascimento e Timeline_Falecimento. Se eu fazer ManyToOne a classe Evento terá que ter o atributo intervalo, assim como as classes Nascimento e Falecimento. Qual dessas soluções seria melhor?
Pessoa{
id nome dtNascimento dtFalecimento
}
Evento{
id titulo descricao //timeline?
}
Timeline{
id intervalo Collection(eventos nascimentos falecimentos)
addEvento(evento) addNascimento(nascimento) addFalecimento(falecimento)
}
Nascimento{
id pessoa //timeline?
}
Falecimento{
id pessoa //timeline?
}
//Unica classe com atributo que diferencia
NomeClasse{
id pessoa n/m //timeline?
}
EDIT:
Eu pensei assim: Se um intervalo da classe Timeline tem uma lista de eventos, ela também terá as lista de falecimentos e nascimentos. Assim eu teria que criar essas classes. O problema neste caso é que se o relacionamento for OneToMany vai ser gerado automaticamente mais três tabelas. Se eu fizer ManyToOne as listas não existirão na classe Timeline que passará a ter somente o atributo intervalo e as classes Evento, Nascimento e Falecimento passam a ter um atributo do tipo Timeline. A conclusão que eu cheguei que não importa qual tipo de relacionamento que eu escolha eu vou ter que ter uma ou duas classes para representar Nascimentos e Falecimentos
Exemplo de como deve ficar na view.
Answer: Eu faria assim:
Teria na mesma tabela o nascimento e o falecimento, e quando quizesse calcular quem nasceu e quem faleceu num determinado intervalo de tempo faria uma query:
<code>SELECT (campos que ache necessário mostrar) FROM pessoa
WHERE dataNascimento BETWEEN 'dataA' AND 'dataB'
OR dataFalecimento BETWEEN 'dataA' AND 'dataB'
</code>
Espero ter ajudado.

OneToMany ou ManyToOne?


Hazard Function

Question: The rate is the expected number of events per some unit (time, or spatial). $\text{Rate}=\frac{\text{numbers of events}}{\text{the length of time interval}}.\ldots (1)$
(Reference: https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen).
The definition of hazard function (or, hazard rate) is "the instantaneous rate of death at time $t$, given that the individual survives up to $t$".
The hazard function $h(t)$ can be defined as
$$h(t)=\lim_{\Delta t\to 0} \frac{Pr(t\le T<t+\Delta t|T\ge t)}{\Delta t}.\ldots (2)$$
(Reference: Lawless, J. F. (2011). Statistical models and methods for lifetime data (Vol. 362). John Wiley & Sons.).
My question is why $h(t)$ is not defined as $\frac{\text{NUMBER of death at time t, given that the individuals survive up to t}}{\Delta t}$?
More Specifically, why is the numerator of equation (2) probability? Why is it not number of death?
Comment: You can only die once.
Comment: In nature, $h(t)$ is a parameter (non-random) but not a statistic (random).
Comment: @StijnDeVuyst But, as the James. Bond franchise showed _You Only Live Twice_ !
Answer: You are confusing two very different things. The definition of $h(t)$, which is just a deterministic function $h:[0,+\infty]\to[0,+\infty]$, and the estimator $\hat{h}(t)$ of $h(t)$, which is a statistic, i.e., a function of your random sample from the population, and thus a random variable itself1.
The definition of hazard rate is what you report (not sure why the dots, I just removed them):
$$h(t)=\lim_{\Delta t\to 0} \frac{Pr(t\le T<t+\Delta t|T\ge t)}{\Delta t}$$
Now, suppose that for a given problem you don't know the expression of $Pr(t\le T<t+\Delta t|T\ge t)$, so you can't compute the above limit. If you can sample from the population, you can estimate it. Now, we need to show that
$$\hat{h}(t) = \frac{\text{number of deaths at time } t}{\text{number of individuals at risk at time } t}$$
is a reasonable estimator of $h(t)$.
Basically, the problem here is that $\text{number of individuals at risk at time } t$ is a really confusing terminology and the authors shouldn't have used it. Anyway, since, given a fixed time $t$, no individual dies exactly at $t$, the numerator must be intended as $\text{number of deaths between time } t \text{ and time } t+\delta t$, where $\delta t$ is suitably small (it's an estimate, after all). Of course, only people who were still alive at time $t$ could die in $[t, t + \delta t]$. Now, the ratio
$$\hat{Pr}(t\le T<t+\delta t|T\ge t) = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{\text{number of individuals alive at time } t}$$
is a frequentist estimate of $Pr(t\le T<t+\delta t|T\ge t)$: this seems intuitive to me, but I add a detailed explanation as requested by the OP. Feel free to skip this part.

Let $T$ be the random variable expressing the time of death of an individual. We want to estimate $Pr(t\le T<t+\delta t)$. We could then draw a random sample $D=\{T_1,\ldots,T_N\}$ of iid random variables, which in practice means following a group of similar individuals until they die. Of course, since you can only die once, we cannot follow the same individual across multiple lives, as opposed to when we throw the same coin multiple times to estimate $Pr(\text{Heads})$. We need to follow a group of individuals, instead. Now, as explained in introductory probability courses, an estimate of $Pr(t\le T<t+\delta t)$ based on $D$ is just
$$\hat{Pr}(t\le T<t+\delta t) = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{N}$$
However, we really want to estimate
$$Pr(t\le T<t+\delta t|T\ge t) = \frac{Pr((t\le T<t+\delta t) \cap (T\ge t))}{Pr(T\ge t)} $$
The estimate for the denominator is obvious: someone will die at a time $T\ge t$ iff he's alive at time $t$, thus
$$\hat{Pr}(T \ge t) = \frac{\text{number of individuals alive at time } t}{N}$$
For the numerator, since the event $t\le T<t+\delta t$ is included in  the event $T \ge t$, $(t\le T<t+\delta t) \cap (T\ge t) = t\le T<t+\delta t$. Thus
$$\hat{Pr}(t\le T<t+\delta t|T\ge t) = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{\text{number of individuals alive at time } t} $$

Thus,  $\hat{h}(t)$ defined as
$$\hat{h}(t)=\frac{\hat{Pr}(t\le T<t+\delta t|T\ge t)}{\delta t} = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{(\text{number of individuals alive at time } t) \times \delta t}$$
is a reasonable estimator of $h(t)$. I guess that the definition used by your book is trying to get at the same estimator, in a very convoluted way,. Probably, what the authors mean is that not all individuals alive at time $t$ are likely to die in a subsequent short time interval. Intuitively, the longer the time interval $\delta t$, the larger is the number of "at risk" individuals, among all individuals alive at time $t$. If we suppose that the number of individuals that, at time $t$, are at risk of death in $[t,t+\delta t]$, is equal to $(\text{number of individuals alive at time } t) \times \delta t$, then we get
$$\hat{h}(t) = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{\text{number of individuals at risk at time } t}$$
which is the definition reported by your book.

1 to be precise, $\hat{h}(t)$ is a random process, not a random variable: however, for each fixed $\bar{t}\in[0,+\infty]$, $\hat{h}(\bar{t})$ is a random variable.
Comment: @ABC thanks to you for suggesting it. It's all too easy, after a few years of dealing with conditional probabilities, how unintuitive some results are the first time you meet them. What's intuitive for me now, definitely wasn't when I started. It's not always easy to write answers on a site where the public goes from real giants in this field, to passionate learners who maybe started their journey in Statistics just a couple years ago :)
Comment: Not sure what you mean with " anyone stops deriving".  If you're asking me "is $\hat{h}(t)=\frac{\hat{Pr}_{[t,t+\delta t]}(t)}{\delta t} = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{(\text{number of individuals alive at time } t) \times \delta t}$ a valid estimator for $h(t)?" then my answer is "yes". But your book is citing a slightly different formula, so I kept going on to show you how you can get to your book's formula.
Comment: If anyone stops deriving the estimate of $h(t)$ in this equation, $\hat{h}(t)=\frac{\hat{Pr}_{[t,t+\delta t]}(t)}{\delta t} = \frac{\text{number of deaths between time } t \text{ and time } t+\delta t}{(\text{number of individuals alive at time } t) \times \delta t}$, doesn't it suffice?
Comment: It also seems to me $\hat{Pr}_{[t,t+\delta t]}(t)$ is an estimate of $Pr(t\le T<t+\delta t|T\ge t)$. But I can't provide any explanation. Could you please explain it?
Comment: @ABC yep, sure, but I'm a bit busy this weekend, so I'm not sure if I'll be able to write it before Monday. However, rest assured I'll do it :) in meantime, you may want to read a bit about conditional probability. Are you familiar with the concept that conditional probability $Pr(A\vert B)$ is a valid probability measure on the sample space $B$?
Comment: Okay. I am familiar with the conditional probability. But I will review it. Thank you.
Answer: By definition, the hazard rate is the rate of death of a population of arbitrary size. The hazard rate you propose - let us call it $\widetilde{h(t)}$ - would be defining what you are interested in implicitly as a function of the population size $S$. In particular, the relationship between the original $h(t)$ and your $\widetilde{h(t)}$ is given by $S \times h(t) =  \widetilde{h(t)}$. Naturally, you are more interested in a population-size independent function.
Comment: From the reference "Lawless, J. F. (2011). Statistical models and methods for lifetime data (Vol. 362). John Wiley & Sons", they told estimate of hazard function $\widetilde {h(t)}=\frac{\text{number of death at time t}}{\text{number of individuals at risk at time t}}$. But in my proposed $\widetilde {h(t)}$, the denominator comes a time interval. Could you please explain it further?
Comment: Well, when you divide number of deaths by number of individuals at risk at time $t$, all you do is constructing $\widetilde{h(t)} = \dfrac{S(t) \times \mathbb{P}( t\leq T \leq t + \delta t|T\geq t)}{S(t) \times \delta t}$ where $S(t)$ denotes the population size at time $t$. So it is different from what you proposed to do up in the question, and should be correct (because $S(t)$ cancels).

Hazard Function


How do I create simple auto code generator?

Question: I'm trying to create a simple form where people input in some values and on submit auto generates the code below the form. Which then they can copy to use.
i.e.
Input 1 width(px) - 200

Input 2 height(px) - 300

Input 3 content - Hello world

Submit button
[code to copy]

[div width="200px" height="300px"]Hello world[/div]

[/code to copy]

Comment: Are you trying to build/use a parser?
Comment: Thank you Jared! That's exactly what I'm trying to build. I just didn't know what to search for.
Answer: This can be done in real time, no need to submit.
Here: http://jsfiddle.net/NzFeb/
$("input").keyup(function() {
    $("#result").text(
        '
' + $("#content").val() +
        '
');
});

To simplify the code i used the library jQuery.

jQuery site
How to set up jQuery in your site
Comment: You might want to mention something about jQuery, though.
Comment: Thank you so much! This is exactly what I was after. How do I go about having multiple of these on the same page though?
Comment: Hi, one more question - How can I have it so that the result html code is displayed when the page loads, even if nothing is entered into the inputs?
Comment: Just run the function when the page load. You can instead of declare the function in the body, declare it separately `function assembleDiv() {...}` and just call it like `$("input").keyup(assembleDiv)` and on the page load `assembleDiv();`
Answer: Try:
Width: <input id="width" type="text" />

Height: <input id="height" type="text" />

Content: <input id="content" type="text" />

<button id="go">Go</button>

<textarea id="code" cols="30" rows="10" ></textarea>
document.getElementById("go").onclick = function() {
document.getElementById("code").innerHTML = "
" + document.getElementById("content").value + "
";

};
as seen here: http://jsfiddle.net/69q57/13/
Comment: @Muddles glad to help. don't forget to vote up helpful answers and mark as answer whatever you ended up going with.


Probablity of a random variable

Question: I really feel ashamed to ask this question however I don't have time for revision. Also not a native English speaker, so excuse my lack of math vocabulary.
I am writing a program that requires assigning probabilities to variables then selecting one randomly.
Example:
Imagine that I have I coin, I would like to assign the probably of 70% to heads and 30% to tails. When I toss it I would like to have 70% chance that the heads appears and 30% tails.
A dumb way to do it is to create an array of cells insert the heads 70 cells and the tail in 30. Randomize them and select one randomly.
I would like to be pointed to how I can do it mathematically,  Without creating the array.
Edit 1: I also would like to point out that I am not limited to 2 variables. For example lets say that I have 3 characters to select between (*,\$,#) and I want to assign the following probably to each of them * = 30%, \$ = 30%, and # = 40%.
That's why I did not want to to use the random function and wanted to see how it was done mathematically.
Comment: What is the question?
Comment: I would like to be pointed to how I can do it mathematically,  Without creating the array.
Comment: whatever language you are using to write your program, there is always a random() method/function/procedure. Generate a random number between o and 1, and if it is greater than 0.7 say it's tails, otherwise it's heads.
Answer: Throw your (fair) coin four times. Amongst the 16 possible results, decide that 3 results mean character *, 3 others mean character $, and 4 others mean character #. This leaves you with 6 unallocated results. If one of these is the result of the throw of your four coins, decide that this round was not successful and throw the coin again four times to apply the same allocation procedure. If this new round fails, starts again, and so on until you get one of the 10 allocated results. The mean number of rounds before you are able to produce a character is only 1.6 hence the mean number of coin tosses is 6.4.
Comment: Same spirit (These are very common "interview" questions): Suppose you have a rand7 function that generates integers 1 through 7 each with prob. 1/7. How to get the function rand4 (from rand7) that generates integers 1 through 4 each with prob. 1/4? One thing I don't like about these solutions is that you may need to do infinite coin tosses before you can actually generate one sample.
Comment: + 1 for the answer. However Stephan has posted a good one.
Comment: Quote: *I did not want to use the random function*... ??
Comment: What I meant is to use the built in random function. Sorry for this mate.
Comment: @Anon Exactly. I was thinking the same thing.
Comment: So, *I did not want to use the random function* means that you want *to use the built in random function*. O well... :-)
Comment: Again dude sorry for that :-( don't make me feel guilty about it. I have already given you +1. I cannot give you a +2, can I?
Comment: @Anon *you may need to do infinite coin tosses*... This is wrong, there is even a theorem stating the opposite... :-) (Do you know that, if your misgivings about this procedure are real, you might as well decide that the best way to inflate a flat tyre is to open the valve and to wait for the oscillations in the ambient pressure to inflate the tyre all by themselves?)
Comment: thedethfox: Just trying to understand what was your question, after all. And I am afraid I still don't get it.
Comment: @did, fair enough, I like to abuse infinity :) You may need to do an arbitrarily large number (put your favorite natural number here) of coin tosses before you can actually generate one sample.
Comment: @Anon True and off the point: for all practical purposes, the number of coin tosses will be finite, and even rather small.
Comment: @did BTW, I think infinity works too. I guess you were thinking about Kolmogorov's zero-one law. The fact that it is a zero-probability event doesn't mean you will avoid it, isn't that correct?
Comment: @Anon No. You might as well say that to draw at random a number between 0 and 1 will yield the result 42. *Almost sure* statements are the strongest possible ones in probability hence one may never *avoid an event* more strongly than by making sure its probability is zero.
Comment: @did No. Draw at random a real number between 0 and 1. Wait, what you get should not have happened almost surely. I won't get 42 as it is not in my sample space.
Comment: @Anon And what if your sample space is $(\mathbb R,\mathcal B(\mathbb R))$ endowed with the restriction to $[0,1]$ of the Lebesgue measure on $\mathbb R$? This modelization of the experiment is as legitimate as the ones you may have in mind since all yield exactly the same set of results. (By the way, what you mean by *what you get should not have happened almost surely* is opaque to me.)
Comment: @did How about the discussion here (we are going off-topic anyway): http://math.stackexchange.com/questions/41107/zero-probability-and-impossibility
Comment: @did BTW, reading my first comment, you may have taken it offensively, that was not my intention. If that is the case, my apologies. I find these (your answer) methods elegant, but they have the weakness I mentioned. My method (answer) is much worse :)
Answer: Stefan Hansen's answer is obviously correct. I myself took this as a "programming question," and here is a one-liner :)
Let $X$ be uniformly distributed on $[0,1]$. Let "Heads" correspond to $1$, and "Tails" correspond to $0$. Then, the random variable $Y = \min\{\lfloor \frac{10X}{3} \rfloor, 1\}$ has the desired properties.
Answer: Let $X\sim U(0,1)$ be uniformly distributed over $(0,1)$. Then $X$ has distribution function
$$
F_X(x)=P(X\leq x)=x,\quad x\in (0,1).
$$ Define a new variable $Y$ by
$$
Y(\omega)=
\begin{cases}
1,\quad &\text{if }X(\omega)\leq 0.7,\\
0,&\text{if }X(\omega)>0.7,
\end{cases}
$$
or in other words $Y=1_{\{X\leq 0.7\}}$. Then
$$
P(Y=1)=P(X\leq 0.7)=0.7,\qquad\text{and}\qquad
P(Y=0)=0.3,
$$
Now let $1$ mean heads and $0$ mean tails. In R this easily done by x=runif(1) y=(x<=0.7).

This extends naturally to several variables. If you want probabilities $30\%$, $30\%$ and $40\%$ then let
$$
Y(\omega)=
\begin{cases}
0, \quad &\text{if }X(\omega)\leq 0.3,\\
1,&\text{if }0.3<X(\omega)\leq 0.6,\\
2,&\text{if }X(\omega)>0.6.
\end{cases}
$$
Do you see the pattern?
Comment: thumbs up (+1). But again I have to revise my math as I have not used probability since years and now it looks like voodoo to me.
Answer: Mathematically: Let X be a random variable on $\{T,H \}$ such that $X(T)=0.3$ and $X(H)=0.7$.
Using R (a commonly used statistical software), and following your suggested method:
coin <- c("H","H","H","H","H","H","H","T","T","T")
sample(coin, 100, replace = TRUE)
the above will give you 100 results of tossing a coin as you described.
A more straightforward way:
a <- runif(100, 0, 1)
b <- a < 0.3
the above will give you a vector with the results of 100 coin tosses of your coin, where the value TRUE in the vector stands for a result of Tail.
Comment: + 1 for the answer. However Stephan has posted a good one.

Probablity of a random variable


OracleDataSource cannot implement createConnectionBuilder() in javax.sql.Datasource

Question: I am currently working on upgrading from Java 8 to 11 for my employer but we are running into an issue that we can't seem to figure out and can't find any help via other posts anywhere. Essentially when doing a maven install, the build fails with the error:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project <project>: Compilation failure
[ERROR] <project>.java:[15,8] createConnectionBuilder() in oracle.jdbc.datasource.impl.OracleDataSource cannot implement createConnectionBuilder() in javax.sql.DataSource
[ERROR]   return type oracle.jdbc.datasource.impl.OracleConnectionBuilderImpl is not compatible with java.sql.ConnectionBuilder

I've looked all over to see what is going on with this, tried to update versions in the pom. When looking at the java class it points at, there is no javax.sql.DataSource in the class anywhere and the line is pointing at the class declaration where OracleDataSource is implemented. There is only one class where we import javax.sql.DataSource but I can't seem to find any link between that class and the other one using the OracleDataSource, so I'm at a bit of a loss. I get the feeling I'm missing something very easy and I'm overlooking it or something. Thanks in advance for any help!
Have tried to update other dependencies within the pom, have tried to clean and then install with maven outside of our custom build script. Have tried altering imports of the OracleDataSource (we import oracle.jdbc.pool and tried to change to oracle.jdbc.datasourc.impl)
Answer: What it means is that your driver is not compatible with Java 11 and does not implement the new method derived from  the java 11 version of javax.sql.DataSource - createConnectionBuilder
You need to upgrade the Oracle driver to a version compatible with java 11.
Here is a list of the oracle drivers with their respective java version: https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html
Comment: Just want to check as ojdbc8 (version 188.8.131.52.09) is a dependency in maven, I was under the impression that would bring the jar in when built.


Why does django pgm crash when entered number exceeds DecimalField max_digits?

Question: I have the following field in my Django model:
price = models.DecimalField(max_digits=8, decimal_places=2, default=0)

and the following code in my form:
price = forms.DecimalField(widget=forms.NumberInput(attrs={'step': '0.01', 'text-align': 'right;'}))

(BTW, the text-align doesn't work - different problem, I think)
It works when displayed in a form. In fact, when I try to use more than 2 decimal places, the form pops up a message:

However, if I enter too many digits, as in:

Django throws the following error:

InvalidOperation at /balancer/set_security_prices/2017-10-14
  []
Request Method:   POST Request
URL:  http://localhost:8000/balancer/set_security_prices/2017-10-14
Django Version:   1.9.1 Exception Type:   InvalidOperation Exception
Value:     [] Exception
Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py
  in format_number, line 200 Python
  Executable:   /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
  Python Version:   3.5.1

The is_valid() check I do before saving the data doesn't trap the problem. This doesn't make sense to me. Shouldn't Django protect against this or must I add try ...except code?
Thanks!
Answer: your first validation error generated by browser, and you should to add validation for max length to the input if you want the same effect
for example:
price = forms.DecimalField(
     widget=forms.NumberInput(
         attrs={'step': '0.01', max='999999', 'text-align': 'right;'})
         #                     ^^^^^^^^^^^^^
)

Comment: Works! Although the syntax for the max is 'max': '999999'  Still not sure why Django generated the too many decimals error but not the too many digits error. Seems like it should.  Thanks for the help!
Comment: Wait, perhaps the 'step' is throwing that to many decimal places error. OK, think I'm good now. Thanks!
Comment: glad to help you.


How to use hash_map in C++ for string key and int value

Question: Can someone give an example how to use hash_map in C++ with string as a key and integer as a value?
Is something like hash_map h;
a valid syntax? Do I explicitly have to define a hashing function or there is a predifined one for string keys?
Comment: C++11 has `std::unordered_map`, TR1 has `std::tr1::unordered_map`, Boost has `boost::unordered_map`. If the test environment supports neither, you'd have to implement your own.
Comment: Use std::unordered_map, not hash_map.
Comment: I know about it, but I want to be able to compile on compilers that do not support c++11. I participate in algorithms contests and I cant be sure that the test environments support the standart
Answer: Take a look at the documentation here, the example shown uses strings as keys and int as values (sometimes it is better to just check the docs first then ask here on so : D).
To be more precise:

you have to specify the key type, the value type, a hash function and a comparison function in the template
you can either construct your own hash function or use a default functor provided by the libs by instantiating a template for hash
for accessing the values just use the keys as if they were the index of an array

(I'm not pasting the code, you can find it in the documentation)
Comment: I do not know, I was sticking to the question desiderata : ) (Btw the story is the same, just check the documentation first)
Comment: Do you think the test environment will happen to have technology as outdated as the STL installed?


Guessing What Data Was Observed Based On The Model?

Question: Suppose I fit a Survival Cox-PH Regression Model in R and get the following results:
Call:
coxph(formula = Surv(time, status) ~ age + sex + ph.ecog, data = lung)

             coef exp(coef)  se(coef)      z        p
age      0.011067  1.011128  0.009267  1.194 0.232416
sex     -0.552612  0.575445  0.167739 -3.294 0.000986
ph.ecog  0.463728  1.589991  0.113577  4.083 4.45e-05

Likelihood ratio test=30.5  on 3 df, p=1.083e-06
n= 227, number of events= 164
   (1 observation deleted due to missingness)

Based on these results, I can infer information such as:

The number of observations
The number of events
The number of variables
The estimate for the effect of each variable

My Question: Given this information, is it possible to simulate the covariate and response information for n = 227 such observations - such that if a similar Cox-PH model was fit to these newly simulated 227 observations, the resulting regression coefficients would approximately be equal to the original regression coefficients? Can I try to guess (and recreate)  observations might have been observed based on the regression model coefficients?
For example, I know that if I were to "fix" the covariate information for a group of n = 227 "arbitrary created" patients, I could then simulate their survival times (e.g. https://cran.r-project.org/web/packages/simsurv/index.html) - however, if I were to then fit a Cox-PH model to these observations, the model coefficients would not necessarily be close to the original model coefficients.
In general, is this possible to do? Only given the above model summary, could I try and somehow generate the original dataset that this model was trained on?
Thanks!
Note: I realize there are probably an infante number of n = 227 samples that can be randomly simulated such that a Cox-PH Model produces the same regression coefficient estimates as above.
Comment: I want to comment here that if someone goes full Bayesian, they could sample from the posterior distributions to create very plausible datasets (given that model was correctly specified, estimated, etc.).
Answer:
Given this information, is it possible to simulate the covariate and response information for n = 227 such observations - such that if a similar Cox-PH model was fit to these newly simulated 227 observations, the resulting regression coefficients would approximately be equal to the original regression coefficients?

Yes. Earlier, you asked a question about how to simulate survival times.  Simply use the method described there but specify the effects of covariates to be what you see in output of your summary call.
Comment: In addition, the input space has 3x227 dimensions and the output has only 3 dimensions (or 6 if you include the standard errors of the coefficients). It is like estimating a sample based on it's mean. You can not get to know the values of the individuals. But, you can generate a sample that corresponds to the output. Is that what you mean?
Comment: @ Demetri Pananos: Thank you for your answer! What I meant by this question, I was interested in knowing if it is possible to "guess" the covariate information belonging to the patients that this model was built on.
Comment: @stats_noob do you mean by 'guess' something like estimate whether the ages had been between 0-10 years or between 50-60 years? That's information which you can not obtain from that output since the output is the same regardless of how the input is shifted.
Comment: @ Sextus Empiricus: thank you for your reply! I think thats what I had in mind : can I try to reverse engineer the medical information  (e.g. age, sex, ph.ecog) and survival times of each patient in this dataset?
Answer:
In general, is this possible to do? Only given the above model summary, could I try and somehow generate the original dataset that this model was trained on?

You'll need additional information about the data to get the distribution of the covariates correct. Even then, you won't match the data exactly, but you'll get closer.
There are answer on Stack Exchange that explain how to simulate survival times from a Cox-PH model. See here, here, and here. Each of these answers use the method in Blender et al (2005) to simulate survival times: invert the cumulative hazard function and plug in uniform random variables.
Your simulation will include the correct effect of each covariate, but you won't be able to know the distribution of the covariates. You know the log hazard of sex is $-0.55$, but you don't know if this was estimated from 10, 50, 100, 200, etc men. You won't know the distribution of age either. Was the study restricted to 50-70 year olds? What were the ages of each person. You can usually find a demographics table that lists the distributions of important variables. If you include this in your simulations, you'll be able to more accurately reproduce survival times.
This additional information will only get you so far. You'll never be able to reproduce the original data exactly. Like you said, there are many datasets that will produce identical or nearly identical parameters.


@protocol não está funcionando

Question: Estou implementando um protocolo mais o mesmo não está conseguindo efetuar a chamada do delegate:
if ([self.delegate respondsToSelector:@selector(addCard)]) {
    [self.delegate addCard];
}

ViewController.m
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@protocol ViewControllerDelegate <NSObject>

-(void)addCard;
@end

@interface ViewController : UIViewController{
}

@property (nonatomic, weak) id <ViewControllerDelegate> delegate;

- (IBAction)setCard:(id)sender;

@end

#import "ViewController.h"
#import "PSWallet.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize delegate;

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)setCard:(id)sender {

    if ([self.delegate respondsToSelector:@selector(addCard)]) {
        [self.delegate addCard];
    }
}
@end

PSWallet.m
#import <Foundation/Foundation.h>
#import "ViewController.h"

@interface PSWallet : NSObject<ViewControllerDelegate>

@end

#import "PSWallet.h"

@interface PSWallet ()

@end

@implementation PSWallet

-(void)addCard{

    NSLog(@"not work");
}

@end

Answer: Seu delegate é um id<ViewControllerDelegate> e na definição do protocolo ViewControllerDelegate o método addCard não é opcional. Sendo assim a checagem [self.delegate respondsToSelector:@selector(addCard)] é teoricamente desnecessária.
Seu código deveria funcionar. Você está setando o delegate no seu ViewController? Há ao menos uma referência strong para ele?
Seu código compila e funciona bem aqui setando o delegate.

@protocol não está funcionando


Different inside v home page in custom Wordpress theme

Question: I want to use a different header style for the home page than for inside pages of my site. Specifically, I want the header section to be less tall on the inside pages.  Should I use a different header.php file for the home page? If so, how?
I'm having a hard time getting ideas using Google, so if anyone has a helpful link to the appropriate resource that'd be great.
Answer: WordPress has a home page boolean function is_front_page() (true if is front page otherwise false)
Add a class to the header/body/whatever parent so
<header class="header<?php if(is_front_page()){ ?> home_header<?php } ?>">

and simply reference the class in CSS.
WordPress codex reference
Comment: Thank you! I'm having a browse through the list of Wordpress functions now, there's a lot of useful stuff in there.


Somando valores com AngularJS

Question: Estou tentando fazer um trabalho simples de faculdade porem estou travado em uma coisa, eu tenho uma lista de objetos com propriedades:
$scope.items = [
  {title: 'Chuveiro Elétrico', quantidade: 4, potencia: 3500},
  {title: 'Ferro Elétrico', quantidade: 1, potencia: 1000},
  {title: 'Ar condicionado', quantidade: 2, potencia: 1900}
];

E eu precisava criar uma função para somar somente os valores das potencias de cada item, se alguém tiver alguma solução simples, ou me indicar o caminho de como resolver isso.

function CartCtrl($scope) {

  //******************************************************************************************************************************************************************CALCULO DAS CARGAS *********************************************************************************************************************************************//

  //setting variables to 0
  $scope.tamRes='0';
  $scope.comodos='0';
  $scope.tomadasCozinha='0';
  $scope.tomadas='0';
  $scope.ilum='0';

  $scope.calculaIluminacao = function(){
    $scope.ilum=parseInt($scope.comodos)*100;
    return $scope.ilum;
  }

  //functions
  $scope.calculaTomCozinha = function(){
    if($scope.tamRes <= 15 ){
      $scope.potCozinha=600;
      return $scope.tomadasCozinha=1;
    } else if($scope.tamRes > 15 && $scope.tamRes <= 30 ){
      $scope.potCozinha=1200;
      return $scope.tomadasCozinha=2;
    }else if($scope.tamRes > 30 && $scope.tamRes <= 250 ){
       $scope.potCozinha=1800;
      return $scope.tomadasCozinha=3;
  }
  }

  $scope.calculaTomadas = function(){
    if($scope.tamRes <= 8 ){
      $scope.potTomada=100;
      return $scope.tomadas=1;
    } else if($scope.tamRes > 8 && $scope.tamRes <= 15 ){
      $scope.potTomada=300;
      return $scope.tomadas=3;
    }else if($scope.tamRes > 15 && $scope.tamRes <= 20 ){
      $scope.potTomada=400;
      return $scope.tomadas=4;
    }else if($scope.tamRes > 20 && $scope.tamRes <= 30 ){
      $scope.potTomada=500;
      return $scope.tomadas=5;
    }else if($scope.tamRes > 30 && $scope.tamRes <= 50 ){
      $scope.potTomada=600;
      return $scope.tomadas=6;
    }else if($scope.tamRes > 50 && $scope.tamRes <= 70 ){
      $scope.potTomada=700;
      return $scope.tomadas=7;
    }else if($scope.tamRes > 70 && $scope.tamRes <= 90 ){
      $scope.potTomada=800;
      return $scope.tomadas=8;
    }else if($scope.tamRes > 90 && $scope.tamRes <= 110 ){
      $scope.potTomada=900;
      return $scope.tomadas=9;
    }else if($scope.tamRes > 110 && $scope.tamRes <= 140 ){
      $scope.potTomada=1000;
      return $scope.tomadas=10;
    }else if($scope.tamRes > 140 && $scope.tamRes <= 170 ){
      $scope.potTomada=1100;
      return $scope.tomadas=11;
    }else if($scope.tamRes > 170 && $scope.tamRes <= 200 ){
      $scope.potTomada=1200;
      return $scope.tomadas=12;
    }else if($scope.tamRes > 200 && $scope.tamRes <= 220 ){
      $scope.potTomada=1300;
      return $scope.tomadas=13;
    }else if($scope.tamRes > 220 && $scope.tamRes <= 250 ){
      $scope.potTomada=1400;
      return $scope.tomadas=14;
    }
    }

  //Example Array
  $scope.items = [
    {title: 'Chuveiro Elétrico', quantidade: 1, potencia: 3500},
    {title: 'Ferro Elétrico', quantidade: 1, potencia: 1000}
  ];

  //Remove button
  $scope.remove = function(index) {
    $scope.items.splice(index,1);
  };

  $scope.in= {
    title: '',
    quantidade:0,
    potencia:0
  };

  //Sum the potency
  $scope.$watchCollection('items',function() {
    $scope.total = 0;
    angular.forEach($scope.items, function(value, key) {
      $scope.total += value.quantidade * value.potencia;
    })
  });

  $scope.addItem = function () {
    $scope.items.push($scope.in);
    $scope.in = {
      title: '',
      quantidade:0,
      potencia:0
    };
  };

  //******************************************************************************************************************************************************************CALCULO DE DEMANDA *********************************************************************************************************************************************//

};
*{
  margin:0;
  padding:0;
  box-sizing:border-box;
  list-style:none;
  text-decoration:none;
}

body {
 font: 15px/1.3 'Open Sans', sans-serif;
}

.wrap{
  width:600px;
  margin:0 auto;
  text-align:center;
  border-radius:4px;
  border:1px solid black;
}
h1{
  background:#34495e;
   color: #FFF;
 font-size: 64px;
 font-family: 'Cookie', cursive;
 font-weight: normal;
 line-height: 1;
 text-shadow: 0 3px 0 rgba(0,0,0,0.1);
}
h2{
  font-family: 'Cookie', cursive;
  font-size:44px;
  background:#34495e;
  color: #FFF;
  font-weight: normal;
 line-height: 1;
  text-shadow: 0 3px 0 rgba(0,0,0,0.1);
}
h3{
  font-family: 'Cookie', cursive;
  font-size:44px;
  background:#34495e;
  color: #FFF;
  font-weight: normal;
 line-height: 1;
  text-shadow: 0 3px 0 rgba(0,0,0,0.1);
}

<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/css?family=Cookie|Open+Sans:400,700" rel="stylesheet">

Cálculo de Demanda

Dados da residência

  Tamanho da residência (m²): <input type="text" ng-model="tamRes">

  Quantidade de Cômodos: <input type="text" ng-model="comodos">

  Quantidade de tomadas: {{tomadas}} - ({{potTomada}}W)

    Quantidade de tomadas da cozinha: {{tomadasCozinha}} - ({{potCozinha}}W)

  Iluminação residencial: {{comodos}} - ({{ilum}}W)

Aparelhos

   {{item.title}}

   Quantidade: <input type="text" ng-model="item.quantidade"/>

   Potência unitária : {{item.potencia}}(W)

   Potência total  : {{item.potencia * item.quantidade }}(W)

    <button class="delete" ng-click="remove($index)">Remover</button>

Adicionar aparelhos

    Nome do aparelho : <input type="text" ng-model="in.title">

  Quantidade : <input type="text" ng-model="in.quantidade">

  Potência unitária : <input type="text" ng-model="in.potencia">

    <button ng-click="addItem()">Adicionar</button>

Carga total instalada: {{total+potCozinha+potTomada+ilum}}(W)

Potência de demanda total: {{totalTomadasIlu}}(W)

Answer: Você pode usar o $watchCollection dentro do seu controller.
$scope.$watchCollection('items',function() {
  // Função disparada sempre que o objeto $scope.items sofrer alterações
  $scope.total = 0;
  angular.forEach($scope.items, function(value, key) {
    $scope.total += value.quantidade * value.potencia;
  })
});

function CartCtrl($scope) {
  $scope.items = [
    {title: 'Chuveiro Elétrico', quantidade: 4, potencia: 3500},
    {title: 'Ferro Elétrico', quantidade: 1, potencia: 1000},
    {title: 'Ar condicionado', quantidade: 2, potencia: 1900}
  ];
  $scope.remove = function(index) {
    $scope.items.splice(index,1);
  };

  $scope.in= {
    title: 'Title',
    quantidade:0,
    potencia:0
  };

   $scope.$watchCollection('items',function() {
    $scope.total = 0;
    angular.forEach($scope.items, function(value, key) {
      $scope.total += value.quantidade * value.potencia;
    })
  });

  $scope.addItem = function () {
    $scope.items.push($scope.in);
    $scope.in = {
      title: '',
      quantidade:0,
      potencia:0
    };
  };
};

   {{item.title}}
    <input type="text" ng-model="item.quantidade"/>

    Potência unitária :
    {{item.potencia}}

    Potência total : {{item.potencia * item.quantidade }}

  <button ng-click="remove($index)">Apagar</button>

 <form>
  Nome do aparelho : <input ng-model="in.title">
  Quantidade : <input ng-model="in.quantidade">
  Potência unitária : <input ng-model="in.potencia">
    <button ng-click="addItem()">+</button>
 </form>

Potência Total: {{total}}

Comment: Acho que entendi o funcionamento desse $watchCollection, era o que eu precisava, valeu :)
Answer:
faz assim

let items = [
  {title: 'Chuveiro Elétrico', quantidade: 4, potencia: 3500},
  {title: 'Ferro Elétrico', quantidade: 1, potencia: 1000},
  {title: 'Ar condicionado', quantidade: 2, potencia: 1900}
];

var valor = 0;

items.filter(function(item){
    valor += item.potencia;
});

Somando valores com AngularJS