How to remove ^M ^J characters in linux

Question: I have an external machine which send me results in my Raspberry pi. In my emulator Cutecom I have the results line by line without problems. I use Codeblocks and I wrote my own C application to read these data every 10 seconds. But something strange happens. Sometimes I have the results line by line and sometimes I have the strange characters ^M ^J at the end of each line and as a result I have terrible finals results. I think that these EOF characters are because the external machine has developed in Windows.
The good results
+PARAMETERS: 45 BYTES FROM 0000:0000 (063)
MACHINE_1:(AN=23.45,H=34.56,D=12.34)

The bad results
+PARAMETERS: 45 BYTES FROM 0000:0000 (063)^M^JMACHINE_1:
(AN=21.45,H=33.56,D=10.34)

Ok, until here the only problem is the way the command line shows the result but my results are ok. But if I try to use strtok to get some tokens then I have serious problems because of these characters. What can I do? Can I add something to escape these characters?This is the part of the code which I use to read data from the machine
char buff[300];
memset(buff, 0, sizeof(buff));
for (;;)
{
  n=read(fd,buff,sizeof(buff));
  sleep(1);
  printf("%s", buff);
  printf("\n");
  ....
  ....

Answer: You're just reading blocks of 300 characters, so there is no string termination \0.
You'll have to look at n to see how much data you have read and then process the data before printing it i.e. look for the ^J^M and terminate the line,then continue reading the rest of the data.
FYI ^J^M is Windows line termination (it's just ^J form linux)
The following should read multiple messages and convert ^ and J to \n and ignore ^M.
Note this uses STDIN, not a serial port.
#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv)
{
    int fd=STDIN_FILENO;
    int i,n;
    int c=0;

    char buff[300];
    memset(buff, 0, sizeof(buff));
    for (;;)
    {
        n=read(fd,buff,sizeof(buff));
        for (i=0; i<n; i++)
        {
            switch(buff[i])
            {
            case '^':
                if(c)
                {
                    // ^^ so output first ^
                    putchar('^');
                }
                else
                {
                    // Possible ^M or ^J
                    c++;
                }
                break;

            case 'M':
                if (c)
                {
                    // ignore ^M
                    c=0;
                }
                else
                {
                    // just M
                    putchar(buff[i]);
                }
                break;

            case 'J':
                if (c)
                {
                    // ^J is \n
                    putchar('\n');
                    c=0;
                }
                else
                {
                    // just J
                    putchar(buff[i]);
                }
                break;

            default:
                if (c)
                {
                    // ^ followed by other than J or M
                    putchar('^');
                    c=0;
                }

                putchar(buff[i]);
            }
        }

    }
    return 0;
}

Comment: Is there any example of this kind of implementation??Thanks!
Comment: I'll write one when I get a moment
Comment: As a matter of interest, what device are you reading from (serial?) and why the sleep(1) after the read?
Comment: yes I have a function to open a serial port, a function to configure port with Baudrate. data bits etc and then a function with the above part to read the buffer. The sleep I have it because sometimes I dont have these strange characters but sometimes I have them. Thats why I use it. Furthermore you are right with your comment that the ^M^J character is left over from a previous read. Because in my loop the first time I have exactly the lines and in the second line I have this characters.
Comment: You probably don't need the sleep then. What output do you get with the modification to terminate the string?
Comment: the first time I have +PARAMETERS: 45 BYTES FROM 0000:0000 (063)
MACHINE_1:(AN=23.45,H=34.56,D=12.34) and it's ok, the second time +PARAMETERS: 45 BYTES FROM 0000:0000 (063)^M^JMACHINE_1:(AN=23.45,H=34.56,D=12.34) and the third time something terrible +PARAMETERS: 45 BYTES FROM 0000:0000 (063)^M^J
MACHINE_1:(AN=23.45,H=34.56,^M^JERROR^M^JD=12.34)^M^J
Comment: It looks like the data is backing up between reads, then you're getting several lines at once, you may want to get rid of any sleeps and let read wait for the data, but I'll do a solution that can cope with read multiple messages in one buffer.
Comment: Looking at this, it's weirder than I thought, ^J is \n so I would have expected it to print a newline which implies the actual characters ^ and J are being sent
Answer: I think you can still use strtok() with this. Just add ^M and ^J in the char *delimiters parameter.
Answer: Just execute the command "sed -e 's/\^\M$//g' filename"
or I got this from the website.
#!/usr/bin/python
while True:
  file = raw_input('Input file name:(input "q" to quit)')
  if file == 'q':
      break
  file_ = open(file).read()
  list_ = list(file_)
  new_file = ''
  for x in list_:
      if x != '^' and x != 'M':
          new_file = new_file + x
  file_ = open(file,'w')
  file_.write(new_file)
  file_.close()

How to remove ^M ^J characters in linux


Develop and Test a Facebook application

Question: Typically I develop my websites on trunk, then merge changes to a testing branch where they are put on a 'beta' website, and then finally they are merged onto a live branch and put onto the live website.
With a Facebook application things are a bit tricky. As you can't view a Facebook application through a normal web browser (it has to go through the Facebook servers) you can't easily give each developer their own version of the website to work with and test.
I have not come across anything about the best way to develop and test a Facebook application while continuing to have a stable live website that users can use. My question is this, what is the best practice for organising the development and testing of a Facebook application?
Comment: Can't each developer setup their own Facebook app, but just keep it private? That's what I did with a friend...
Comment: Are you talking about Facebook connect ? because a facebook normal canvas app is separated from normal web site and you can make it live once you have done all the development.
Comment: Hi Arfeen: Ya am talking about fb connect.
Answer: I hope I understood your question correctly.
What we have is 2 versions of our app, that is two applications defined in facebook.
We have the regular version that runs on deploy, and we have the myapp-test version.
this version runs on the domain myapptest.com (or you can use myapp.local).
In your HOSTS file (%winder%\system32\drivers\etc) define this url and redirect it to your own server on localhost (127.0.0.1).
Now, all you need is a config file on each machine that is not updated via source-control.
The localhost (development) version uses the app_id for the myapp-test, and relevant settings.
The deploy uses the other settings.
Then when you deploy you just need to upload your code.

Develop and Test a Facebook application


Git commit reference over tags

Question: We use Git for source code versioning and Bamboo for continuous integration. Few projects in our organization do not tag the code in Git when they release a version to production. When quizzed about this, they say the commits in the specific build will tell the code that went into the production system.
My question is, is it sufficient to have the specific commits pointed to by a Bamboo build. Or we have other advantages of tagging which we do not get without tagging.
One thing I know is that the builds may not be retained in Bamboo (purging) and in the future, I may not have the snapshot of the source code that was in production at some point in time.
Answer: Tags are nothing more than easy to understand names given to specific commits. The main advantage in using them I can think of is that it makes the git repository self-descriptive. You don't have to juggle between git and bamboo to get a correct picture of what version is which. This is especially important if your bamboo server is down (e.g., for scheduled maintenance) or if you ever want to switch to a different CI system.
Answer: So I'll answer this a little farther then tags.
But as to your original question, tags are an immutable reference to a specific time in a commit. As Mureinik has stated, a tag is just an easy reference to a specific hash in your git repository.
But for you second point, Bamboo has a built in Expiry, which also has an exception field.  Any release can be labeled as such and be tagged in the exception list of the expiry (the exception list can be regex i.e. release/1.0.0 matches release.*)

Git commit reference over tags


Sensitivity, Specificity and Misclassification rate

Question: I stumble upon a problem that I'm sure someone else already had.
Assume you have:

A cohort, composed of 10 healthy subjects and 100 diseased subjects.
A model M such that M(patient) = diseased. In other words, each patient is classified as diseased.

At this point we can compute:

Specificity = (TN=100) / (N=100) = 1
Sensitivity = (TP=0) / (P=10) = 0

Till here everything looks fine: the model poorly represents the reality, and the sensitivity captures this fact.
However, the misclassification rate is 0.09, which usually is not that bad.
This bias comes from the small healthy control sample size.
Is there a way to correct this bias, so that the misclassification rate can represent how inaccurate this model actually is?
Answer: There is no bias concerning the misclassification rate, it just measures what it's supposed to measure. As you indicate, misclassification rate or accuracy can be a very misleading measure, especially if the distribution of the classes are unbalanced.
Here are some links about common measures to assess prediction quality:
http://webdocs.cs.ualberta.ca/~eisner/measures.html
http://en.wikipedia.org/wiki/Receiver_operating_characteristic
Answer: Most of your problem comes from the fact that these measures are discontinuous improper accuracy scoring rules.  If you stick with assessing the continuous calibration curve of continuous risk predictions these problems diminish.


Combining multiple rows into one single row in Dataframe in R

Question: Suppose I have a dataframe, which looks like this.
|  Category  |  Text                  |
| :--------: | :--------------------: |
| First      | I am Groot.            |
| First      | We are Groot.          |
| Second     | The Dark Knight Rises. |
| Second     | I am Batman.           |
But we want to combine rows in column Text, which happens to have same value in category column, into one row and make it look like this.
| Category | Text                                 |
| -------- | ------------------------------------ |
| First    | I am Groot. We are Groot.            |
| Second   | The Dark Knight Rises. I am Batman.  |
How do I do that?
Comment: Would answers from [this question](https://stackoverflow.com/questions/38514988/concatenate-strings-by-group-with-dplyr) help you?
Answer: data.table solution:
library(data.table)
dt0 <- data.table(
  Category = c(rep("First", 2), rep("Second", 2)),
  Text = c("I am Groot.", "We are Groot.", "The Dark Knight Rises.", "I am Batman.")
)
dt <- dt0[, .(Text = paste0(Text, collapse = " ")), by = .(Category)]
dt

Explanation: paste0 takes the column Text (which, in data.table syntax is evaluated to dt$Text) and collapses it to a single value. This calculation is performed for each unique value in Category, indicated by by = .(Category).
Comment: But that is exactly what the solution I posted above does. ```dt``` contains 2 rows whereas the original data.table ```dt0``` contains 4.
Comment: My bad, it does
Comment: Hello there, thank you for your response, I want to do reverse actually, i.e. if my dataframe looks like dt alsready and I want to make it look like dt0, what do I do.
Comment: First, you need to define where exactly to split your Text. After each dot?
Comment: I want to compile not separate.


Access local variable from other function PHP

Question: I have a private function which has lots of variables, let's say these: $foo, $bar, $baz.
Inside the function, I call parent::_setViewVars(array('foo','bar','baz'));
This _setViewVars looks so:
protected function _setViewVars($a){
    foreach($a as $v){
        global $$v;
        $this->set($v, $$v);
    }
}

I just want to get rid off cakephp's shit like 80 lines of $this->set('selected_areas',$selected_areas);, that's what this function is for.
_setViewVars cannot access $$v, because it's not a global variable. Given that this function is being called from the context that has these variables, can I reach them somehow?
(by the way if there is a cakephp way of bulk setting view variables with the same names, tell me how -- I haven't found one)
PS: packing everything into an array is NOT a solution, we're talking about thousands of unneccessary square brackets here.
Comment: `global`? Seriously? Just use `compact()` in your _controller actions_ (not in a redundant separate method): `$this->set(compact('foo', 'bar', 'baz'));` That's btw exactly what CakePHP does when baking controllers...
Comment: Take a look at [compact](http://us1.php.net/manual/en/function.compact.php), which creates array useful for your scenario.
Comment: I've tried it: `compact` also does not reach these variables.
Comment: Can you redefine `parent::_setViewVars`? Or skip calling it altogether in favor of your own loop in which you call `->set()`, dealing with output of `compact`?
Answer: What you're looking for is actually pretty standard PHP:
compact()  -  Create array containing variables and their values
Example showing it's use in a CakePHP Action:
$var1 = "I";
$var2 = "love";
$var3 = "pizza!";
$this->set(compact('var1', 'var2', 'var3'));

(might want to try to tone down the hatred a bit - you're more likely to get help that way)


Confidence intervals on model parameters

Question: I have a very basic question about interpreting confidence intervals. Say I use R to fit a linear model to the Nile water flow time series (from the datasets package), like this:
# Flow of the Nile river (10^8 cubic metres per year) between 1871-1971
nile.ts <- data.frame(year = do.call(seq, as.list(attributes(Nile)$tsp)),
           flow = as.numeric(Nile))

# Fit linear function
nile.fit <- gls(flow ~ year, data = nile.ts)

Next, I look at the confidence intervals on the model parameters:
# Look at 95% confidence intervals
intervals(nile.fit)

Approximate 95% confidence intervals

 Coefficients:
                  lower        est.       upper
(Intercept) 4144.217893 6132.173579 8120.129266
year          -3.749313   -2.714305   -1.679298
attr(,"label")
[1] "Coefficients:"

 Residual standard error:
   lower     est.    upper
132.1041 150.5522 175.0363

Here, the coefficient of year in the model is estimated to be $-2.7$ and has a 95% confidence interval of $[-3.7, -1.7]$. I'd read this as meaning I can be pretty confident that there has been a decline in the flow over time. But what if the confidence interval had been $[-3.7, +1.7]$? Since it straddles zero, does this mean that I can't say anything about the trend? Or, can I state that there is no statistically significant trend?
Answer:
Or, can I state that there is no statistically significant trend?

Yes. The coefficient for year would be then not different from 0.
Comment: @ Lyngbakr, you can use a more formal wording that is based on the **p-value** in the model output, which is that: the probability that a coefficient estimate will be at least as large as the observed value when the Null hypothesis is true.


How could I find the sum of digits of $A^{2}$ if $A=102030201$ (no calculator )?

Question:
How could I find the sum of digits of $A^{2}$ if
  $A=102030201$   (Clearly  calculator is not allowed )?

Okay , it could be done by manually calculating the product of $A$×$A.$
But it will be meaningless question
Any help would be much appreciated.
Comment: Well, Comman, that narrows it down to infinitely many possibilities.
Comment: $1+0+2+0+3+2+0+1=9$, therefore divisable by 9. So $A$ is divisable by 9 and so must be $A^2$. So the sum of digits has to be of the form $9k$ with $k\geq 1$
Comment: It's harder to explain then do, but the digits of the product will have a "diagonal sum" symmetry.  The first digit then the next significant digit is $2*1+1*2 = 4$.  Then next is $3*1 + 2*2 +1*3 = 10$ and because we have zeros as "place holders" we don't need to worry about carrying.  Extending it the sum will be $1 + (2*1 + 1*2) + (3*1 + 2*2+1*3) + (1*2 + 2*3 + 3*2 + 2*1) + (1*1 + 2*2 + 3*3 + 2*2 + 1*1)+ (1*2 + 2*3 + 3*2 + 2*1) + (3*1 + 2*2+1*3) + (2*1 + 1*2)+1  = 36$
Answer: $$
\begin{array}{r}\\
&&&&1&&&&&\text{coefficients of  }(x^2+x+1)^0\\
&&&1&1&1&&&&\text{coefficients of  }(x^2+x+1)^1\\
&&1&2&3&2&1&&&\text{coefficients of  }(x^2+x+1)^2\\
&1&3&6&7&6&3&1&&\text{coefficients of  }(x^2+x+1)^3\\
1&4&10&16&19&16&10&4&1&\text{coefficients of  }(x^2+x+1)^4\\
\end{array}
$$
The coefficients of $(x^2+x+1)^k$ can be  calculated recursively in a way similar to the pascal triangle. If the number $a_{i-1,j}$ is the number above $a_{i,j},$ then
$$ a_{i,j}=a_{i-1,j-1}+a_{i-1,j}+a_{i-1,j+1}$$
And $$(x^2+x+1)^4=(x^4+3x^3+x^2+2x+1)^2=\ldots$$
and so we have to sun the digit sum of the numbers of the last line in the triangle, which is $36.$
So simply multiply $A\cdot A$ by hand to get the result fast:
$$102030201 \cdot 102030201 =\\
\begin{array}\\
102030201 \\
\phantom{1}\phantom{1}204060402 \\
\phantom{1}\phantom{1}\phantom{1}\phantom{1}306090603\\
\phantom{1}\phantom{1}\phantom{1}\phantom{1}\phantom{1}\phantom{1}204060402 \\
\phantom{1}\phantom{1}\phantom{1}\phantom{1}\phantom{1}\phantom{1}\phantom{1}\phantom{1}102030201 \\
\hline
10210161916100401
\end{array}
$$

The problem is more interesting if you pose it the other way round.

How can you quickly calculate
  $$(x^4+2x^3+3x^2+2x+1)^2?$$
  You can use a numerical calculator but can't use a CAS that can manipulate formulas.
Answer:
Type  in $$102030201$$ in your calculator, square it to get
$$10410161916100401$$
and from this extract the coefficients of the solution
$$x^8+4x^7+10x^6+16x^5+19x^4+16x^3+x10^2+4x+1$$
Answer: Note $102030201 = 10101^{2}$, so if $A=10101$, then you need $A^{4}$. Note that $A=10^{4}+10^{2}+1$.
So we have $$(10^{4}+10^{2}+1)^{4}=10^{16}+\binom{4}{1}(10)^{12}\cdot (10^2+1)+\binom{4}{2}\cdot 10^{8} \cdot (10^2+1)^{2} + \cdots$$
Looks a bit ugly but i hope this helps.
Comment: why do you think that this helps? Is this simpler than calculating the product by hand?
Comment: @miracle173 i think it helps because all the terms have power of 10 which is easy to add and calculate :)
Comment: in the decimal representation of 102030201 all terms are powers of 10, too. in your representation you have to calculate the $(10^2+1)^i$ powers . I can't see  how this will be simpler.
Comment: @miracle173 Hey listen. you just have to calculate $(10^2+1)^{i}$ for $i=0,1,2,3,4$. I don't think it's difficult at all.
Comment: and then you have to multiply them with $10^{12},10^{8},10^{4}$, and then you have to sum the coefficients of equal powers and then you have to check if there are carries you have to consider and then you can start to add the digits. I think this is only a complicate way to do the multiplication by hand.
Comment: Well i agree it's complicated, but i don't agree with your view that "this is only a complicate way to do the multiplication by hand". Multiplying powers of ten and adding them isn't difficult.
Comment: Ugly as hell, in my opinion.
Comment: After writing an answer to this that is similar (but hopefully more explanitory)  I also come to the conclusion the best thing is to just take pencil and paper and multiply this out by hand.  The alternating zeros keep the multiple column borrowing to a minimum and it's not that hard a product to do by hand.
Answer: It's harder to explain then do, but the digits of the product will have a "diagonal sum" symmetry.  The first digit then the next significant digit is $2*1+1*2 = 4$.  Then next is $3*1 + 2*2 +1*3 = 10$ and because we have zeros as "place holders" we don't need to worry about carrying.  Extending it the sum will be $1 + (2*1 + 1*2) + (3*1 + 2*2+1*3) + (1*2 + 2*3 + 3*2 + 2*1) + (1*1 + 2*2 + 3*3 + 2*2 + 1*1)+ (1*2 + 2*3 + 3*2 + 2*1) + (3*1 + 2*2+1*3) + (2*1 + 1*2)+1  = 1+4 + (1+0) + (1+6)+ (1+9) + (1+6) +(1+0) + 4 +1 = 36$
===   In detail+++++
Note: $(\sum_{i=0}^{n} a_i * 10^i)^2 = \sum_{k=0}^{2n} (\sum_{i+j = k}a_ia_j*10^k)$
e.g.  $abcde = a^2*10^8 + (ba+ab)*10^7 + (ca +b^2 ac)*10^6 + (da+bc + cd+ac)*10^5 + (ae + bd + c^2 +db + ea)*10^4 + (be + cd + dc + eb)*10^3 + (ce + d^2 + ec)10^2 + (de+ed)*10 + e^2$
So $102030201^2 = $
$10^{16} + (2+2)*10^{14} + (3 + 4+ 3)*10^{12} + (2+6+6+2)*10^{10} + (1 +4+9+4+1)*10^8 + (2+6+6+2)*10^6 + (3+4+3)*10^4 + (2 + 2)*10^2 + 1=$
$10^{16} + 4*10^{14} + 10^{13} + 16*10^{10}+ 19*10^8 + 16*10^6 + 10^5 + 4*10^2 + 1=$
$10410161916100401$
And the sum is $36$.
One can also note that $102030201$ has a distinct symmetry that would come with $10101^2 = 102030201$ (by the same reasoning; $10101 = 1*10^8 + (1+1)*10^6 + (1+1+1)*10^4 + (1+1)*10^2 + 1*10^0$)
So $A^2 = 10101^4$ which... well, you can get creative:
$(10^4 + 101)^4 = 10^{16} + 4*10^{12}*101 + 6*10^8*101^2 + 4*10^4*101^3 + 101^4=$
$10^{16} + 4*10^{12}*101 + 6*10^8(10201) + 4*10^4*1030301 + 104060401=$
$10,000,000,000,000,000 +$
$00,404,000,000,000,000 +$
$00,006,120,600,000,000 +$
$00,000,041,212,040,000 +$
$00,000,000,104,060,401 =$
$10,410,161,916,100,401$
.....
Actually, .... just doing the multiplication by hand isn't that hard:
$\_\_ 102030201$
$\times 102030201$
$==========$
$00000000102030201$
$00000020406040200$
$00003060906030000$
$00204060402000000$
$10203020100000000$
$=================$
$10410161916100401$
The zeros and the symettry make it not so hard.
Answer: I have noticed, and I can't prove this yet, that if the digit sum of $x$ is $z$, then digit sum of $x^2$ is $z^2$.
Comment: I can help, because it cannot be proved. Take the example of $x = 102030201$, then $z = 9$, but $x^2$ has digit sum of $36$ as seen by other answers, which is slightly lower than $z^2 =  81$.
Comment: @mdave16 Well, that's true. I wonder if it works only when $\log_{10}{n}$ is smaller than some constant $k$?


Where is the most "realistic" CDP-S100's volume level that is closest to real acoustic piano?

Question: As a very beginner I've bought the CDP-S100. It seems enough at least for first year of leisurely learning.
But while practicing, I noticed that I apply different force to keys depending on volume level set on my piano, because I unconsciously try to reach the same sound volume. For example, when I practice at night with 20% volume level set, I hit keys way more intensively than at midday with 50% volume level set, or then when I use my headphones.
So, the question is - what volume level should I set to make it sound as if it were an acoustic piano, with the similar loudness/hitforce ratio? 50%? 100%? I'm aware that there are no exact standards here, but anyway I want to have some approximate basis to keep in mind.
Unfortunately I have no ability to compare it to acoustic piano in the same room now, so maybe someone's already done such experiment? :)
Thanx a lot in advance for any clue :)
Answer: Without knowing that particular model, I'd guess you probably need "full volume" to properly match an acoustic.
If you ever try actually accompanying people live in a 'gig' situation, you will quickly discover a digital piano just cannot reach the levels you can with an acoustic, without further amplification.
Pianos are pretty loud.
That doesn't actually mean you have to use it on full all the time - because if you were actually in a gig situation, you'd probably be in a larger or noisier space & you would need the extra level.
In the living room… not so much. I'd drop the levels to what you are comfortable listening at for your particular playing style of any given piece. Don't let the volume slider affect your playing.
Comment: Just checked in my studio - I have several k'bds set up, and a studio acoustic piano. A Roland (2x 7w, same size speakers) sounds about the same as the acoustic piano when the vol. pot. is full on. Which agrees with your idea. +1.
Comment: Hitting keys hard rarely does any damage - to the piano - maybe to one's ears! Leaving the volume up high will make you become far more discening as to how you press the keys - a good thing.
Comment: That's when you start learning to play gently too.
Comment: For a little light nocturne, sure… but if you're getting your best Jerry Lee Lewis impression down pat, you probably need to pull that slider back a ways;) That's why I said don't let the slider dictate how hard you play.
Comment: The point is that the most comfortable level for me is "as quiet level as possible" :) And I'm afraid I can hit my keys way more than it should be done because of it :)
Comment: ...so, according to your answer, seems like it would be better to set the highest level to push myself to control the volume more attentively at the beginning of learning. Am i right?
Comment: @Tim thanx a lot!
I guess my neighbours won't sleep tonight :)


One to one async communication between services

Question: I'd like to communicate two services in a GCP App Engine project asynchronously. GCP docs states that Pub/Sub may be used to achieve many-to-many asynchronous communication. I was wondering if I could and if it is a good practice to use Pub/Sub for one to one async communication.
I thought I colud have a topic to send requests from the client service to the server service. Prior to send the request, the client would create a new "ephimeral" topic with a random name and supply the topic in the message payload and would pull the topic. The server would publish the reponse to the supplied topic in the payload.
Is that crazy? I not, should the client remove after it receives the response. Will be the latency an stoper?
Thanks
Answer: About the best practice it looks like Google Cloud Recommends to use targeted HTTP requests, this is based on this link
About using pub/sub with App Engine, it is also mentioned that this can be done as well, and it will let you achieve communication between apps, but it looks like this could be limited to application modules in the same project as per this link, and in order to achieve low latency you would need to cache the publisher client by initializing it as a global variable. But even with this configuration, it may end up existing a lot of latency as you would be sending 2 pub/sub messages.
I believe that I would use the tradicional http Request, but if you want to try it out, there is a tutorial on how to set up app engine in order to use pub/sub at this other link


How to install extra bin files when `npm install` is given `-g` flag?

Question: Is there some way to install only part of a NodeJS project when run via npm install, but to install additional features when npm install -g is used?
I have a library with a command-line interface, however the CLI is not useful to any downstream projects using my library.  So when those projects pull in my library, I don't want them to pull down dependencies like chalk that are only used for the CLI they will never touch.
However if an end user decides to install my library globally on their system with npm install -g then I want the CLI installed, and via the bin section in package.json, placed in their path so they can run it like any other program.
I can't work out how to do this without splitting the CLI into a separate package.  The options I have investigated are:

Put the CLI dependencies as devDependencies.  This prevents chalk etc. from being installed in downstream projects, but the drawback here is that the user must npm install -g in development mode, which means they get the test framework and linting tools installed as well even though they will never use them.
Put the CLI as a separate NodeJS package/module.  The drawback here is that it makes testing difficult (as often the CLI and library are modified at the same time and used for testing new features), and developers wanting to contribute to the library will have to stuff around with linking the two packages so although it would work, it's less than ideal from a workflow perspective.
Put the CLI in a folder inside the main package, and create another package.json in there just for the CLI, pulling in the main project via npm install ...  This works until you get to the install point, when you realise that there is no way to install the CLI once the package has been published.  npm install @my/library will only install from the package.json in the project root, there's no way to say "oh also install the package in the cli subdirectory too."

Ideally what I would like is this:

npm install @my/library - run by a developer wanting to use the library in their project.  Adds the library only to their project's dependencies, ignores both CLI and any dependencies the CLI needs.
npm install -g @my/library - run by an end-user, installs library and CLI globally on their system, including the CLI dependencies, and adds the CLI to the user's path via the package.json bin section.
npm install --dev - used by developer contributing to the library to install the test framework so they can run the unit tests before submitting their code for inclusion.
Not having to split the CLI into a separate project.

Is this possible?
Answer:
Is there some way to install only part of a NodeJS project when run via npm install, but to install additional features when npm install -g is used?

You can write a postinstall script that uses is-globally-installed (or another similar package) to check if the module is installed globally, and then run whatever is appropriate to install the CLI (perhaps npm install -g for a separate package that just has the CLI).
Comment: This is a great idea, but how do I pass `npm` parameters though?  For example if the original caller wrote `npm install -g --prefix /my/install/folder` is there an easy way to ensure those extra parameters get passed through to the child `npm` process?  I know the `make` program has the special `$(MAKE)` variable which expands to the command with all the extra parameters set but I can't see if `npm` has an equivalent.  I'm assuming it needs one because when I tried running `cd cli && npm install -g` inside the `post-install` script it froze.
Answer: Well I came up with a workaround.
I put the CLI back to development-only (with its requirements in devDependencies so it could be used by local devs, but they wouldn't get pulled in to downstream projects using the library).  I then created another package for the CLI, but all it was is a package.json file and nothing else.
What this package does is depend on the main library, plus only the dependencies needed by the CLI.  Then it uses the bin section to point to the CLI inside the main library, so no code is needed in this package - it is literally just one file.  Like so:
{
  "name": "@my/library-cli",  // new module to install the CLI
  "bin": {
    "myprog": "./node_modules/@my/library/bin/myprog.js"  // the command is inside the dependency
  },
  "dependencies": {
    "@my/library": "*",       // require the library itself where the CLI code sits
    "command-line-args": "*"  // dependency needed by the CLI
  }
}

The only drawback with this is that this new package's dependencies need to be kept in sync with the main library's devDependencies (at least the deps required by the CLI) but as they won't change often in my case I can live with that.
I did try the postinstall hook as @Trott suggested but it didn't seem to work:
"scripts": {
  "postinstall": "[ $npm_config_global == 'true' ] && (cd cli && npm install -g)"
}

For some reason it was incredibly slow and seemed to get stuck in a loop, trying and failing to install over and over.  I'm also not sure it would've respected being launched via a command like npm install -g --prefix /my/install/folder as that non-standard prefix may not get passed through to the child npm process.


Help solving very complex first order ODEs using ode45 - MATLAB - movement of water

Question: I am trying to solve this complex set of first order ODEs using ode45 on MATLAB. They describe the change in volume of water in the inner layer ($X_I$) and outer layer ($X_O$) of the Venus Flytrap's upper leaf (trap). This movement of water is what allows the trap to snap shut. I am looking to solve the ODEs for time for different parts of the prey capture process (which will have different conditions - eg. for the closing process, where the trap moves from an open to semi-closed state, we have $u_a$ and $u_c$ equal to zero.) These u terms are water transport rates driven by various gradients, $\alpha$ is the water supply rate from the roots and $\mu$ is the water consumption rate.
$dX_O/dt = \frac{\alpha X_O^2}{X_O^2 + X_I^2} + u_h + u_a - u_c -\mu X_O$
$dX_I/dt = \frac{\alpha X_I^2}{X_O^2 + X_I^2} - u_h - u_a + u_c -\mu X_I $
Where:
$X_O + X_I = 1$
$k_t(s^-1) = 10$
$k_f(s^-1) = 2$
$k_d(s^-1) = 0.000045$
$\alpha (h^-1) = 1$
$\mu (h^-1) = 1$
and
$u_h = k_t max\{X_I(t) - X_O(t),0\}\delta _t(t)$
$u_a =\left\{
  \begin{array}{@{}ll@{}}
    k_f X_I(t) \delta _t(t), & \text{if}\ C \geq 14 \\
    0, & \text{if}\ C<14 \end{array}\right.$
where $\delta_ t(t) = \left\{
  \begin{array}{@{}ll@{}}
    1, & \text{if}\ 0 \leq t \leq 0.3 \\
    0, & \text{if}\ t>0.3 \end{array}\right.$
$u_c(t) = k_d \delta _c(t)$
where $\delta _c(t) =\left\{
  \begin{array}{@{}ll@{}}
    1, & \text{if}\ T_{start} \leq t \leq T_{start}+T_D \ (T_D=15 \ hours) \\
    0, & \text{otherwise} \end{array}\right.$
So far I have attempted to create a script file which defines the variables:
a = 3600;
mu = 3600;
Xo = 1 - Xi;

if (0 <= t1) && (t1 <= 0.3)
    Dt1 = 1;
else
    Dt1 = 0;
end

Uh = 10*max((Xo - Xi),0)*d;

if C >= 14
        Ua = 2*Xi*Dt1;
    else
        Ua = 0;
    end
if (0 <= t2) && (t2 <= 54000)
    Dc = 1;
else
    Dc = 0;
end

Uc = 0.000045*Dc;

where a represents $\alpha$ and Dt and Dc represent $\delta _t$ and $\delta _c$ respectively. Note that I converted the values of $\alpha$ and $\mu$ into seconds.
I created two times, t1 and t2 so that I could put $T_{start}$ as $0$ for $\delta _c(t)$.
If anyone could help me I would be extremely grateful, I've spent about 15 hours on this now and am still getting nowhere, despite my numerous searches online for hints.
Comment: What do you mean by $k_t(s^-1)$?  Does it perhaps mean that the dimensions of $k_t$ are $s^{-1}$?
Comment: It's some kind of rate so 'per second'
Answer: If $X_I + X_O = 1$, then $\frac{d}{dt}(X_I+X_O) = 0$, which implies $\alpha = \mu$.  We can also simplify the problem by letting ode45 compute, say, $X_O(t)$ and then computing $X_I(t) = 1 - X_O(t)$.
MATLAB's ode45 and its siblings are passed a handle to a function of $t$ and $X_O$ that computes $\frac{dX_O}{dt}$.   That function may be built in two stages.  First we write a function with all the parameters as inputs (besides $t$ and $X_O$).  It may look like this:
function xdot = dxodt(t, x, kt, kf, kd, alpha, mu, C, Tstart, TD)
  c = alpha * x^2 / (2*x^2 - 2*x + 1);
  deltat = 1.0 * (0 <= t && t <= 0.3);
  uh = kt*max(1-2*x,0)*deltat;
  if C >= 14
    ua = kf * (1-x) * deltat;
  else
    ua = 0;
  end
  deltac = 1.0 * (Tstart <= t && t <= Tstart + TD);
  uc = kd * deltac;
  xdot = c + uh + ua - uc - mu*x;
end

We then fix the values of the parameters and invoke the solver by some code like this:
function venusflytrap
  %VENUSFLYTRAP simulate Venus Flytrap

  kt = 10;       % 1/s
  kf = 2;        % 1/s
  kd = 0.000045; % 1/s
  alpha = 3600;  % 1/s
  mu = alpha;
  Tstart = 0;
  TD = 15*3600;
  % These values are uneducated guesses.
  C = 1;
  xinit = 0;
  Tfin = 1;

  options = odeset('stats','on');
  fh = @(t,x) dxodt(t, x, kt, kf, kd, alpha, mu, C, Tstart, TD);
  sol = ode45(fh, [0, Tfin], xinit, options);
  plot(sol.x,sol.y)
end

If these two functions are placed in the same file, venusflytrap should come first, and the file should be named venusflytrap.m.
Comment: Thanks so much! I don't have access to MATLAB at the minute to give this ago but as soon as I do I'll let you know how I get on!
Comment: @maria1991 If the preceding answer has given you full satisfaction, **please** check the answer.


ASP.NET Razor Pages erro ao processar a requisição

Question: Estou implementando um exemplo utilizando o ASP.NET Razor Pages e ao tentar acessar a página Index tenho o erro de que ouve erro na requisição.

Error.
  An error occurred while processing your request. Request ID:
  0HLA7N3BM0ANB:00000001
Development Mode Swapping to Development environment will display more
  detailed information about the error that occurred.
Development environment should not be enabled in deployed
  applications, as it can result in sensitive information from
  exceptions being displayed to end users. For local debugging,
  development environment can be enabled by setting the
  ASPNETCORE_ENVIRONMENT environment variable to Development, and
  restarting the application.

Index.cshtml
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

Contacts

<form method="post">

                ID
                Name

            @foreach (var contact in Model.Customers)
            {

                    @contact.Id
                    @contact.Name

                        edit
                        <button type="submit" asp-page-handler="delete"
                                asp-route-id="@contact.Id">delete</button>

            }

    Create
</form>

Index.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPagesContacts.Data;
using Microsoft.EntityFrameworkCore;

namespace RazorPagesContacts.Pages
{
    public class IndexModel : PageModel
    {
        private readonly AppDbContext _db;

        public IndexModel(AppDbContext db)
        {
            _db = db;
        }

        public IList<Customer> Customers { get; private set; }

        public async Task OnGetAsync()
        {
            Customers = await _db.Customers.AsNoTracking().ToListAsync();
        }

        public async Task<IActionResult> OnPostDeleteAsync(int id)
        {
            var contact = await _db.Customers.FindAsync(id);
            if(contact != null)
            {
                _db.Customers.Remove(contact);
                await _db.SaveChangesAsync();
            }

            return RedirectToPage();
        }

        public void OnGet()
        {

        }
    }
}

Comment: Deu certo sim, valeu
Comment: No configure tem esse `if` `if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }`
Comment: Tem sim esse if
Comment: Já debugou? quando acontece o erro?
Comment: tem dois OnGet? não pode! ou seja, OnGet e OnGetAsync faz a mesma coisa e o erro acontece ai, então comente OnGet
Comment: Mesmo um sendo Async?
Comment: Sim ... !!! mesmo sendo Async e mesmo tendo um outro assinatura... Razor Pages tem essas inconveniencias
Comment: A lógica é: ele tem que executar somente um dos métodos? como está o dois o Razor Pages não sabe qual executar e ai da a exceção.
Comment: ?Deu certo?    ....
Answer: O erro ocorre porque o Razor Page não consegue saber em tempo de execução qual dos dois métodos GET criados no seu código, ou seja, OnGet e OnGetAsync é para ser executado, resumindo não pode coexistir os dois ao mesmo tempo no código, porque fazem a mesma coisa, gerando uma exceção por causa disso.
Referencias

Introdução a Páginas do Razor no ASP.NET Core
ASP.NET Core - Aplicativos ASP.NET MVC mais simples com Páginas Razor
Answer: No web.config altere(ou adicione caso não exista) o value da tag environmentVariable para Development:
<environmentVariables>
        <environmentVariable name = "ASPNETCORE_ENVIRONMENT" value="Production" />
</environmentVariables>

<configuration>

  <system.webServer>
    <handlers>
      <add name = "aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath = ".\Application.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables>
        <environmentVariable name = "ASPNETCORE_ENVIRONMENT" value="Production" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

Fonte: https://stackoverflow.com/questions/39737585/asp-net-core-deployment-to-iis-error-development-environment-should-not-be-enab
Caso não resolva só avisar.
Comment: Estou utilizando o vscode e criei o projeto usando o dotnet new razor
Comment: Eu não tenho em meu projeto um web.config, somente o appsettings.json.
Comment: Criei em outra pergunta sobre como colocar em Development https://pt.stackoverflow.com/q/264319/5846


GItlab does not send email on new issue

Question: GItlab does not send email on new issue, but do it for issue closing and comments. How can I enable it?
Answer: Any notification rule issue on GitLab are referenced ("featured") in Issue 2669.
A redesign is in progress (issue 1808), but not there yet.
Proposals already exists (issue 2466, issue 1448 ), where you can select the people in a team you want to be notified:

That feature request is managed here: "Improve email/notification system".

GItlab does not send email on new issue


How can I set up the equipment I have so I can play the guitar with a backing track (laptop) and using headphones?

Question: I have a guitar, two amps, a pedal and a pair of headphones.
My target is to somehow set these devices up in a way that would allow me to play the guitar along with a backing track coming from a laptop. The output doesn't need to be the amps speaker, I'll happily use just the headphones as I practice at night times. In fact, I prefer using headphones.
My first amp is a Stagg that came with my first guitar as a bundle. One input and a jack for the phones.

The second amp is a Crate CA30. It's for acoustic which will work, but there's more jacks.

Finally, the pedal I have is the Behringer LX1-1 with the below plugs.

What I've tried so far is the below using the Crate amp.

Hooked up the guitar to the INPUT jack of the pedal
Hooked up the pedal from the MONO (AMP) jack to the Input 1 jack of the amp
Hooked up the laptop to the Input 2 jack of the amp
Hooked up the headphones to the Line Out jack of the amp.

From 1 to 3, all worked fine and all sounds came out of the amp but number 4 didn't work. No sound was coming out of the headphones when I connected them to Line Out. After a few web searches, I read that Line Out, although not a headphone jack, should still work but it would be less audible. I can't hear anything though and the headphones work.
Ideally, I'd solve the headphones issue, or alternatively another setup combination if possible. I can't think of anything else I can do with these specific devices.
The easiest thing to do would be to buy another amp with an AUX input but I'm having difficulty selling or even giving away the two amps I have so I don't want a third amp in the house without being sure that I have absolutely no solution with the two I already have.
Any ideas on how I can setup these devices are welcome as well as any other suggestions for a minimal approach to this.
Comment: Easy enough to check line out works: plug from it into the other amp, plug guitar into 1st amp. Turn up each vol. control. Sound should come out from at least the 2nd amp.
Comment: So you are saying that up to step 3 everything works, and you hear guitar and backing coming out of the amp? So the sole problem is headphones not giving you sound when plugged into Line Out on the amp?
Comment: Yes, exactly. Another possibility may be that the Line Out isn't working, but before I get it checked (apparently they charge an arm and a leg round my ends to check this), I'd like to make sure that my approach is correct.
Comment: That's brilliant, thanks. Will try the soonest.
Answer: It might be because the laptop is converting the audio signal from stereo/mono to the opposite then back again?
Make sure the male heads all have 2 lines near the tip (TS vs TRS vs TRRS)
1 Line = Mono, 2 Lines = Stereo, 3 Lines = Stereo + Microphone
A lot of times guitar players use A TS Cable (1 Line) which will only send audio out of the left headphone, in that case you use the mono out of the pedal rather than stereo.
TRS (2 Lines) will send audio to left and right headphones. I don't know if there's any cons to using TRS vs TS as your guitar cable. As far as I know it just duplicates the signal to the right side.
(Also for future reference, XLR is mono)
If you go back and forth between Mono/Stereo it might get mixed up and not know where to send the signal. Experiment with TS/TRS cable types and the mono/stereo output of the pedal.
Guitar -> Input of Pedal
Pedal Stereo Out -> Input 1 on Amp
Laptop Audio Out (1/8" to 1/4" male to male) TRS -> Input 2 on Amp
I'm not sure exactly how the Insert input works on the amp, according to the manual:
Insert - Use this jack to add external effects to the signal. The ring = send (line out), tip =return (line in), sleeve = ground. This jack can also be used to "chain" multiple ampli-fiers together, since connecting to this jack does not interrupt the signal going to
From my understanding you use it for effects which means you can try plugging the pedal into insert, for example -
Guitar -> Input 1 Amp
Laptop Audio Out (1/8" to 1/4" male to male) - > Input 2 Amp
Pedal Stereo/Mono (try both) Out -> Insert Amp
Headphones -> Line Out
Another alternative and IMO the easiest solution would be to get an audio interface, preferably with 2 inputs, quality entry level ones are about $100-$200. This offers an external audio card to your PC which will allow you to record from your amp into your computer directly with high quality and low latency (immediate sound monitoring, no delay) I have the Focusrite 2i4 but right now I really want the Motu 2, which has super low latency and a high quality digital to audio converter. In your DAW set audio output hardware to be your audio interface (it should be ASIO audio driver to minimize latency) - 44100 or 48000 sample rate with 128 or 256 buffer size - then adjust latency compensation. Also in your DAW you can create a separate audio track for each input of the interface. (Channel 1, input 1 - Channel 2, input 2). Headphones out from the audio interface. Then you can either monitor the sound through the DAW (introduces computer processing) or if your interface has a direct monitor (Focusrite does) then you can listen to it straight to the headphones without going through your computer. Using an interface also allows you to add even more effects in your DAW with audio effect plugins.
Another sound solution would be to get a mixer like Behringer or Mackie, send the laptop and amp into different inputs on the mixer then headphones out of the mixer. This would be a direct analog signal with no computer processing. Mixers tend to be a bit cheaper and you can scale up with a lot of inputs at a much more reasonable price.
Sorry  if you know all of this, I figured I'd explain as much as possible just in case
Comment: If you read the description of insert, it says that it uses a special cable that has send and return on the tip and ring of the TRS plug. You'd need an Y cable that splits it to two TS plugs to connect it to a normal effects box.
Comment: Answer voted for because of the audio interface suggestion. Turns out the Line Out probably doesn't work on the Crate so I bought an audio interface as you suggested which was by far the best option with minimal equipment. So glad I did that instead.
Answer: Why not just use the Stagg as a headphone amp? Steps 1-3 are fine, although you might try "insert" on the crate instead of input 2 for the computer input, it might be TRS which would give you both stereo channels instead of just one (in mono of course but you won't lose any audio).
Step 4 would be Crate line out to Stagg input
Step 5 is headphones to Stagg headphone jack
If you don't care about using the Behringer for your guitar tone you can go guitar and computer straight to the Crate and use the Behringer as your headphone amp in the same manner as the Stagg.


Binary logistic regresion bonferoni correction

Question: In our study, we applied a bacward stepwise elimination logistic regression analysis between the two groups over a wide variety of variables.
There was such a criticism of the referee.
Your results, although statistically are approximating an odds ratio of 1. Especially considering the amount of variables you are reporting, it would be good practice with a Bonferoni correction instead of assuming the usual p-value of .05 for rejection of the null- hypothesis.
What do you think the referee meant and what kind of solution should be applied?
Answer: One of the goals of frequentist hypothesis testing is to maintain the probability of a Type I Error (T1E). When testing many hypotheses we usually maintain the family wise error (FWER), which is the probability of making at least 1 T1E.
Why do we have a problem? Suppose we maintain an the probability of T1E of $\alpha$ for each test and define $V = \sum_{i=1}^{m_0} V_i$ where $V_i$ is the indicator of making a T1E for hypothesis $i$, $m_0$ is the number of correct null hypotheses and $m$ is the number of hypotheses. Furthermore, assume of tests are independent.
$P(V \geq 1) = 1 - P(V = 0) = 1 - P(\cap_{i=1}^{m_0} V_i = 0) = 1 - (1 - \alpha)^{m_0}. $
As you can see, the more hypotheses we test the probability of making at least one T1E increases.
In order to maintain the FWER we can apply a variety of multiple comparisons corrections, one of the most standard corrections is the Bonfferroni correction. It will guarantee that the FWER will be maintained at a specified level. The correction is conservative (meaning it will maintain a FWER at probability smaller than $\alpha$), and depending on the scenario other method might be preferable (such as Holm or Hochberg).
Note, that even with the correction the analysis is still not valid. Since you have used backward stepwise algorithm to choose the variables, and this selection must be taking into account in the analysis. You might be better using Lasso logistic regression with the appropriate correction, see Lee, Jason D., et al. "Exact post-selection inference, with application to the lasso." The Annals of Statistics 44.3 (2016): 907-927, and this question.


How can i debug why files are not being created when using migrate files to media module?

Question: I run the drush migrate-duplicate-file-detection migd8_grants_media_step1 successfully, and then run the node migration and step 1, however the media is being populated with the name only, the file is not attached nor are the files being moved over to the sites default/files/grants directory as they should
Steps to reproduce
this is my step 1 yml.
<code># File to Media Migration configuration for grants Media migration

id: migd8_grants_media_step1
label: Grants Media Step 1
migration_group: cncs
source:
  key: migrate
  plugin: media_entity_generator_d7
  entity_type: node
  bundle: grants
  langcode: und
  d7_file_url: 'https://www.externalwebsite/sites/default/files/'
  field_names:
  - field_files

destination:
  plugin: entity:media

process:

  bundle:
    plugin: default_value
    default_value: document

# Using the alt tag if available, else the file name.
  name:
    plugin: media_name
    source: file_name

# This process plugin will skip the whole row if a existing media is found.
  existing_media_file:
    plugin: check_media_duplicate
    source: target_id

# This process plugin will skip the whole row if a duplicate document is found.
  unique_file_id:
    plugin: check_duplicate
    source: target_id

# Map the field
field_media_document/target_id: target_id
field_media_document/target_id:
  plugin: media_file_copy
  move: FALSE
  reuse: TRUE
  path: 'public://grants/'
  source: file_path

langcode: und

uid:
  plugin: default_value
  default_value: 1
</code>
Comment: You might want to edit to format the code exactly as your current file is. Your copy/paste looks to have lost the indentation, which is important for YML
Comment: are errors not shown on Watchdog? Usually missed files means, that source path is incorrect.
Answer: You have an an error in your yml file, should be:
<code># Map the field
field_media_image/title: title
field_media_image/target_id:
    plugin: media_file_copy
    move: FALSE
    reuse: TRUE
    path: 'public://grants/'
    source: file_path

langcode: langcode
</code>
Comment: hi since its not an image but a bundle of type document, i will use field_media_document where you have field_media_image
Comment: that worked ! except i used language which was the field name in my source table for the language code
Comment: i am having a different problem with step 2 as described here and the yml in the example does not specifiy a bundle.https://drupal.stackexchange.com/questions/297273/why-is-step-2-of-file-to-media-migrate-giving-me-missing-bundle-error
Answer: the answer was that i had to put the nid in the import so the nid was the same in the source and target content in order for this to work.


Reading a Hex data array byte value from serial port

Question: I have to read a data from Serial port using C program. I am sending Hex array data and the device will response the corresponding response for the request.
I have tried with the GTK+ Serial port Terminal, For Example, if i write data "FC 05 40 2B 15" the device will resturn the response as "FC 05 50 AA 05".
Someone please guide me to get this, i have been trying for so long.
I have attached my code here.
void main()
{
    int fd;
    struct termios SerialPortSettings;
    char write_buffer[512];
    int dispense_card[5] = { 0XFC,0X05,0x40,0x2B,0x15 };
    //char dispense[7] = {0x02,0x31,0x35,0x44,0x43,0x03,0x02};
    int  bytes_read = 0;
    FILE* lfp;
    time_t now;
        time(&now);

    //lfp = fopen("carddispense.log","a+");
    fd = open("/dev/ttyUSB1",O_RDWR | O_NOCTTY);
    if(fd == -1)
    {
            //fprintf(lfp,"\nError! in Opening ttyUSB0 %s", ctime(&now));
        printf("\nError in Opening in ttyUSB0\n");
        exit(1);
    }
    else
        {   printf("\nttyUSB0 Opened Successfully\n");
        //fprintf(lfp,"Card reader has been used %s", ctime(&now));

        tcgetattr(fd, &SerialPortSettings);       /* save current serial port settings */
        cfsetispeed(&SerialPortSettings,B9600);  /* Baud rate for read */
        cfsetospeed(&SerialPortSettings,B9600);

        SerialPortSettings.c_cflag &= PARENB;   // No Parity
        SerialPortSettings.c_cflag &= ~CSTOPB; //Stop bits = 1
        SerialPortSettings.c_cflag &= ~CSIZE; /* Clears the Mask       */
        SerialPortSettings.c_cflag |=  CS8;   /* Set the data bits = 8 */

        SerialPortSettings.c_cflag &= ~CRTSCTS;  /*Turn off hardware based flow control */

        SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Turn on the receiver of the serial port (CREAD) */

        SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY); /*Turn off hardware based flow control */

        SerialPortSettings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* NON Cannonical mode for serial communication */

        SerialPortSettings.c_cc[VMIN]  = 100; /* Read 128 characters */
        SerialPortSettings.c_cc[VTIME] = 0;  /* Wait indefinitely   */

        tcsetattr(fd,TCSANOW,&SerialPortSettings);
        int pos =0,percent_count = 0;
        int i;
        for(i=0;i<5;i++)
        {
            printf("number = %x\t",dispense_card[i]);
            sprintf(write_buffer+(i),"%c", dispense_card[i]);
        }
        printf("write_buffer%s\n",write_buffer);
        //printf("write_buffer length: %d\n",strlen(write_buffer));

        write(fd,write_buffer,strlen(write_buffer));
        close(fd);
    }
}

Comment: There's no such thing as "hex data" (except possibly in the form of a string). Hexadecimal is one of many possible textual representations of numbers. `0xFC` is `252` is `0374` (and CCLII).
Comment: You forgot to mention what the problem is.
Comment: I couldn't  able to get the get the exact data like "FC 05 50 AA 05" using my program. But I able to get the correct response in GTK+ serial port terminal tool
Comment: @molbdnilo or even more :) Binary  11111100(2)
Ternary  100100(3)
Quaternary  3330(4)
Quinary  2002(5)
Senary  1100(6)
Octal  374(8)
Duodecimal  190(12)
Hexadecimal  FC(16)
Vigesimal  CC(20)
Base 36  70(36)
Comment: (1) Your termios configuration does not (but should) clear OPOST in the `c_oflag` member.  (2) The statement  `sprintf(write_buffer+(i),"%c", dispense_card[i])` does nothing but copy a byte; it's a very expensive copy method.  (3) You seem to complain of a read problem, yet have not posted any code related to reading.
Answer: Try this
char tx_buf[5];
char rx_buf[5];

sprintf(tx_buf, "%c%c%c%c%c",0XFC,0X05,0x40,0x2B,0x15);
write(fd, tx_buf, 5);

while (1) {
    int n = read (fd, rx_buf, 5);
    if (n > 0) {
       for(int i=0; i<n; i++) {
          printf("data i: %02X ", rx_buf[i]); //  "FC 05 50 AA 05"
       }
    }
}
close(fd);

Comment: :) Thank you for your piece of code.  The code is not going inside the loop because the "n" value is not returning as greater than 0.
Comment: Try to put "read function" inside "while loop" for waiting until receive serial data (n value more than 0 ).
Comment: look at here for reference https://en.wikibooks.org/wiki/Serial_Programming/termios


Symmetric Matrices with trace zero

Question: Let $M_n$ denote the set of complex matrices of order $n$.
It is well known that if $A\in M_n$ has trace zero then $A$ can be written as $A=BC-CB$, where $B,C\in M_n$.
Is it true that every symmetric matrix $S\in M_n$ with trace zero can be written as $S=RR^t-R^tR$, for some $R\in M_n$?
This theorem is true for real matrices. If $S$ is a real symmetric matrix with trace zero and order $n$ then exists a real matrix $R$ of order $n$ such that $S=RR^t-R^tR$.
Is it true for complex matrices?
Comment: For complex matrices: by symmetric, do you mean [Hermitian](https://en.wikipedia.org/wiki/Hermitian_matrix)?
Comment: @Omnomnomnom For Hermitian matrices with trace zero, the theorem would be $S=RR^*-R^*R$ for some $R$. This theorem is also true. The "real" problem is for "complex" symmetric matrices.
Comment: No, I mean symmetric $(A=A^t)$.
Comment: How to prove the theorem is true for real matrices? Thanks
Comment: @Clin Below you can find the answer for complex matrices. I will try to write the answer for real matrices latter. The proof is simpler. The problem for complex matrices is much more difficult.
Comment: @Clin I wrote below an alternative solution for real symmetric matrices. Notice that the approach used by user1551 at his post on May 13 gives another solution.
Answer: OK, here is a complete answer: every traceless and (complex) symmetric matrix $A$ can be written as a commutator of the form $[R,R^T]$ for some matrix $R$. Since comments have been left to my old answer, instead of editing the old answer, I give a new one here. A similar idea to those employed in my answers to other related problems (see q95537 and q251678) is applicable. The key observation is the following:

Lemma. Suppose $A$ is an $n\times n$ traceless complex symmetric matrix.
(a) When $n$ is odd, $A$ is complex orthogonally similar to a matrix whose last diagonal entry is zero.
(b) When $n$ is even, $A$ is complex orthogonally similar to a matrix whose trailing principal $2\times2$ submatrix and leading principal $(n-2)\times(n-2)$ submatrix are both traceless.

Proof of the lemma. Suppose $n$ is odd and none of the zero diagonal entries of $A$ is zero. As $A$ is also traceless, it must have two diagonal entries $x$ and $z$ such that $x\ne\pm z$. If $s$ and $c$ are two complex numbers such that $s^2+c^2=1$, then
$$
\pmatrix{c&s\\ -s&c}\pmatrix{x&y\\ y&z}\pmatrix{c&-s\\ s&c}
= \pmatrix{\ast&\ast\\ \ast&xs^2-2ysc+zc^2}.
$$
So, to prove the lemma for the odd case, it suffices to show that $xs^2-2ysc+zc^2=0$ is solvable in $(s,c)$. Rewrite the equation as $x+(z-x)c^2=2ysc$. Square both sides, we get $x^2 + 2x(z-x)c^2 + (z-x)^2c^4 = 4y^2(c^2-c^4)$ or
$$
[(z-x)^2+4y^2]c^4 + [2x(z-x) - 4y^2]c^2 + x^2 = 0.\tag{$\ast$}
$$
Since the constant term $x^2$ is nonzero, if the coefficients of $c^4$ and $c^2$ vanish, the equation is insolvable. However, this cannot occur, otherwise we would have $(z-x)^2 = -4y^2 = -2x(z-x)$ and in turn $(z+x)(z-x)=0$, contradicting our assumption that $x\ne\pm z$. Therefore $(\ast)$ is solvable. That is, $A$ is orthogonally similar (via the use of a "complex Givens rotation") to a matrix with a zero diagonal entry. By performing a similarity transform via a permutation matrtix, the result follows.
Now suppose $n$ is even. If $A$ has a pair of diagonal entries $(x,-x)$, the result follows by permutation similarity. On the contrary, if $A$ has have two diagonal entries $x$ and $z$ such that $x\ne\pm z$, then the above argument shows that $A$ is orthogonally similar to a matrix whose last diagonal entry is zero. But then the principal $(n-1)\times(n-1)$ submatrix of $A$ is traceless, symmetric and has odd order. By applying (a) to this submatrix, the result follows. $\square$

Proof of the main statement. We now prove that every complex symmetric matrix $A$ can be written as a commutator of the form $[R,R^T]$. It turns out that the construction of $R$ is fairly simple. Split $R$ into the sum of its complex symmetric part $H$ and complex skew symmetric part $K$. Straightforward calculation shows that $[R,R^T]=2[K,H]$. So the problem boils down to solving $\frac A2=[K,H]$. We will deal with even $n$ and odd $n$ separately.
Case 1: $n$ is even. We will prove by mathematical induction that $\frac A2=[K,H]$ is solvable with a nonsingular $K$. The base case is easy:
$$
\underbrace{\pmatrix{x&y\\ y&-x}}_{A/2}
= \underbrace{\pmatrix{0&-1\\ 1&0}}_K
\underbrace{\pmatrix{y&-\tfrac x2\\ -\tfrac x2&0}}_H
- \pmatrix{y&-\tfrac x2\\ -\tfrac x2&0}\pmatrix{0&-1\\ 1&0}.
$$
Now, suppose the induction hypothesis holds up to matrices of order $n-2$. Consider a traceless symmetric matrix $A$ of order $n$.
$$
\frac A2=\left[\begin{array}{c|c}
A_{n-2}&\begin{array}{cc}\mathbf a_1&\mathbf a_2\end{array}\\
\hline
\begin{array}{c}\mathbf a_1^T\\ \mathbf a_2^T\end{array}&A_2
\end{array}\right],
\quad H=\left[\begin{array}{c|c}
H_{n-2}&\begin{array}{cc}\mathbf h_1&\mathbf h_2\end{array}\\
\hline
\begin{array}{c}\mathbf h_1^T\\ \mathbf h_2^T\end{array}&H_2
\end{array}\right],
\quad K=\left[\begin{array}{c|c}
K_{n-2}&0\\ \hline0&K_2\end{array}\right],
$$
where $A_{n-2},\,H_{n-2},\,K_{n-2}$ are $(n-2)\times(n-2)$ and $A_2,\,H_2,\,K_2$ are $2\times2$. By our lemma, we may assume that both $A_{n-2}$ and $A_2$ are traceless. As $K_2$ is skew symmetric, $K_2=\alpha Q$ for some complex scalar $\alpha$, where $Q=\pmatrix{0&-1\\ 1&0}$. So, the equation $\frac A2=KH-HK$ is equivalent to the following system of equations:
\begin{align}
K_{n-2}H_{n-2}-H_{n-2}K_{n-2}&=A_{n-2},\tag{1}\\
K_2H_2-H_2K_2&=A_2,\tag{2}\\
\pmatrix{K_{n-2}&-\alpha I_{n-2}\\ \alpha I_{n-2}&K_{n-2}}\pmatrix{\mathbf h_1\\ \mathbf h_2}
&=\pmatrix{\mathbf a_1\\ \mathbf a_2}.\tag{3}
\end{align}
By induction assumption, $(1)$ and $(2)$ are solvable and both $K_{n-2}, K_2$ can be chosen to be nonsingular. For $(3)$, since $K_{n-2}$ commutes with $\alpha I_{n-2}$, the determinant of the square matrix on the left side of $(3)$ is $\det(K_{n-2}^2+\alpha^2 I_{n-2})$. As $K_2=\alpha Q$, by scaling $\alpha$ and $H_2$ appropriately, the value of $\alpha$ can be chosen such that it is nonzero and $\det(K_{n-2}^2+\alpha^2 I_{n-2})\ne0$. Therefore $(3)$ is also solvable and $K$ is nonsingular.
Case 2: $n$ is odd. The case $n=1$ is trivial. Now suppose $n\ge3$. By our lemma, we may assume that the last diagonal entry of $A$ is zero. Let
$$
\frac A2=\left[\begin{array}{c|c}A_{n-1}&\mathbf a\\ \hline\mathbf a^T&0\end{array}\right],
\quad H=\left[\begin{array}{c|c}H_{n-1}&\mathbf h\\ \hline\mathbf h^T&0\end{array}\right],
\quad K=\left[\begin{array}{c|c}K_{n-1}&0\\ \hline0&0\end{array}\right],
$$
where $A_{n-1},H_{n-1},K_{n-1}$ are $(n-1)\times(n-1)$. The equation $\frac A2=KH-HK$ is then equivalent to the system of equations
\begin{align}
K_{n-1}H_{n-1}-H_{n-1}K_{n-1}&=A_{n-1},\tag{4}\\
K_{n-1}\mathbf h&=\mathbf a\tag{5}.
\end{align}
By the result for the even case, $(4)$ is solvable with a nonsingular skew symmetric matrix $K_{n-1}$. Hence $(5)$ is also solvable.
Comment: Thank you very much. Your solution is beautiful and very creative.
Comment: @Daniel Thanks for catching the typos. They are fixed now and I hope none remains.
Comment: Very creative answer. I like it. +1.
Comment: @Edwin Thanks for the bounty bonus! I didn't read the bounty conditions carefully and thought it was offered to an alternative answer.
Answer: Here you can find an alternative proof for the real symmetric case. I am writting to answer Clin's question. Notice that the approach used by user1551 at his post on May 13 gives a different solution.
Let $S$ be a real symmetric matrix of order k and trace zero. Let $S=\sum_{i=1}^n\lambda_iv_iv_i^t$ be a spectral decomposition of $S$ with $\lambda_1\geq\lambda_2\geq\ldots\geq\lambda_n$
$(\lambda_i\neq 0)$(Edit: and $v_1,\dots,v_n$ orthonormal).
Define $\beta_i=\lambda_1+\dots+\lambda_i$. Notice that $\beta_n=0$.
Now, $\beta_i>0$ for $i<n$, otherwise $\beta_{i+1}<0$ and $\beta_n<0$.
Define the matrices $V_{k\times n-1}, W_{k\times n-1}$ using the vectors $v_i$ as columns: $V=(v_1,\dots,v_{n-1})$ and $W=(v_2,\dots,v_{n})$. Notice that $V^tV=W^tW=Id_{n-1}$.
Define the diagonal matrix $D_{n-1\times n-1}$ with $\beta_1,\dots,\beta_{n-1}$ in the diagonal.
Notice that $S=\sum_{i=1}^n\lambda_iv_iv_i^t=\sum_{i=1}^{n-1}\beta_iv_iv_i^t-\sum_{i=1}^{n-1}\beta_iv_{i+1}v_{i+1}^t$. Therefore, $S=VDV^t-WDW^t$.
Finally $S=VD^{\frac{1}{2}}W^tWD^{\frac{1}{2}}V^t-WD^{\frac{1}{2}}V^tVD^{\frac{1}{2}}W^t=RR^t-R^tR$, where $R=VD^{\frac{1}{2}}W^t$.
Comment: really grateful for your  answer
Comment: @user1551 Thanks.

Symmetric Matrices with trace zero


"RNGCryptoServiceProvider does not contain a definition for GetNonZeroBytes"

Question: I have the following code. The function is to generate a random ID of a specific size. However i keep getting an error that says

'System.Security.Cryptography.RNGCryptoServiceProvider' does not contain a definition for 'GetNonZeroBytes' and no extension method 'GetNonZeroBytes' accepting a first argument of type 'System.Security.Cryptography.RNGCryptoServiceProvider' could be found (are you missing a using directive or an assembly reference)

I am trying to use the cryptography library in .NET and according to msdn this is one of the functions that can be used in this scenario but for some reason i keep getting this error.
Can anyone help?
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.Text;

namespace ONeRESPONSEAPP
{
    public class IdGenerator
    {
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[45];
            chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider identity= new RNGCryptoServiceProvider();
            identity.GetNonZeroBytes(data);
            data = new byte[maxSize];
            identity.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
    }
}

Comment: @OrvillePatterson: What .Net profile are you targetting?
Comment: The only think I can think of is that there is a `RNGCryptoServiceProvider` in the local namespace. Try: `new System.Security.Cryptography.RNGCryptoServiceProvider()`
Comment: Something wrong is with your .NET, I'm able to compile this code well. What environment are you using?
Comment: I tried it in .NET 3.5, 4.0 and 4.5 (both full and client profile), works perfectly fine.
Comment: its a WP7 app. Im working on the registration module so i'm using this function to generate a random ID.
Comment: @caesay Although, as far as I can tell, it's been supported on everything since .NET 1.1
Comment: @OrvillePatterson With the *same* error? (Then, no idea.)
Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Answer: System.Security.Cryptography.RNGCryptoServiceProvider.GetNonZeroBytes() is not supported by Windows Phone 7.
You might want to use RNGCryptoServiceProvider.GetBytes() instead, it is cryptographic strong as well.


Python threading and handing over values

Question: Im trying to update threads which continuously run with new values every now and then.
class Test:
    def __init__(self, num):
        #testing reasons
        self.num = num

    def printloop(self, num):
        self.num = num
        #running is set to True sometime in the beginning
        while running:
            print(self.num)
            time.sleep(3)
        if not running:
            print("finished")
    def setnum(self, num):
        self.num = num

I create threads like this:
t1 = threading.Thread(target=test.printloop,args=("1"))

This works and prints the proper arg.
But how can I update single threads with new values - if needed? Not all of the threads might need to be updated. The setnum method in my class there is obviously not working since it would update the value for all of the threads.
Do I need to limit the thread lifetime and join and wait for them to finish. Then recreating them with new values?
Or should I define a variable for each thread - how do I do that dynamically?
Or is there a better way im not seeing?
Thanks!
Edit:
I suppose i'll end up with something like:
test1 = Test(1)
..
test5 = Test(5)

t1 = threading.Thread(target=test1.printloop,args=("1"))
t5 = threading.Thread(target=test5.printloop,args=("5"))

and then use a method on each to set the Values?
Comment: What is `run`? something that constantly goes on in background? or some task that can be finished?
Comment: I would like it to run constantly in the background - however I could set a timer on them to re-run them with new values.. My preferred method - if viable - would be to update the running threads without stopping or recreating them.
Comment: test1.setnum('new value') modifies only test1.num. Be careful with the way you initialize args though. It should be args = ('1',) because args is a tuple. So args = ('123') will throw an error because printloop will be called with three arguments '1', '2' and '3'
Answer: For single integer values you can make Test a subclass of thread (and have run call printloop). Then other threads can call setnum safely. Due to the GIL and the fact that you are setting a single value this is safe, if you were doing a more complex update you would have to wrap setnum and the inner loop in printloop in a lock to prevent race conditions.
EDIT: A simple example
from threading import Thread
from time import sleep

class Output(Thread):

    def __init__(self, num):
        super(Output, self).__init__()
        self.num = num
        self.running = False

    def run(self):
        self.running = True
        while self.running:
            print self.num
            sleep(1)

    def stop(self):
        self.running = False

    def set_num(self, num):
        self.num = num

output = Output(0)
output.start()
sleep(3)
output.set_num(1)
sleep(3)
output.stop()
output.join()

Comment: AFAIK, setting an int is not an atomic operation, because it can be written on more than one byte, that means that the thread can be interrupted in the middle of setting the int, and then you've got yourself a race condition.
Comment: Python's GIL means that you can't corrupt Python data internally, so when you set an int the whole int will be set. If this were in a lower level language then yes there's a risk there.
Comment: I dont understand what you mean steve. Can you give me an example? Do you mean doing something like: threading.Thread.test = Test(123) ?


Ordinary differential equation eigenvalues/eigenfuntions

Question: Consider the DE $$y''+\lambda y=0$$ where $\lambda$ is a constant
subject to the boundary conditions $$y(0)=0$$ and $$y(a)=0$$ where $a$ is a positive constant
I want to find the eigenvalues and eigenfunctions related to this problem
My attempt:
The auxiliary equation is $$m^2-\lambda=0\implies m=\sqrt{-\lambda}$$
Thus we have two cases
Case (i)
$$\lambda<0$$ in which we have real different  roots
so let $$\lambda=-k^2\implies m=\pm k$$
thus the solution is $$y=Ae^{kx}+Be^{-kx}$$
Now when $y(0)=0$ we have that $$0=Ae^{k(0)}+Be^{-k(0)}\implies -B=A$$ since $k\ne 0$
Now when $y(a)=0$ we have that $$0=Ae^{ka}+Be^{-ka}\implies \frac{Ae^{ka}}{e^{-ka}}=-B$$ since $a\ne 0$ thus there are no eigenvalues for when $\lambda <0$
Can anyone tell me if i have made a mistake somewhere in this, because i'm unsure what to do from here, i know the next case to check will be when $\lambda>0$ which would give complex roots, but i would like to know if my approach up to now is correct, thanks for taking the time to read this, and any help would be appreciated also i know that when i multiply through by $$q^*=\frac{1}{a_2}e^{\int\frac{a_1}{a_2}}dx=1$$ thus in normal ?self-adjoint form.
Comment: Yes as $\lambda <0$
Comment: I think first part is right. for the second, $\lambda>0$ gives $m=\pm ik$ (with  $\lambda=k^2$). right!
Comment: Yea I've gotten that it's $y=Acoskx+Bsinkx$
Comment: so you you found the answer. good job.
Comment: It's when I substitute the second condition in I can't seem to  simplify it
Comment: With $y(0)=0$ we see $A=0$. With $y(a)=0$ we see $\sin ka=0$ then $ka=n\pi$ that is $k=\dfrac{n\pi}{k}$.
Comment: finally answer is $y(x)=B\sin\dfrac{n\pi}{a}x$, $n\in\mathbb{Z}$ and $B\in\mathbb{R}$.
Answer: Yes, your approach so far is correct. One should also check (preferably first, so you don't forget!) the $\lambda=0$ case: here, it is easy to check that the boundary conditions can't be satisfied.
One can actually extract the general solution from your analysis. In order for there to be a nonzero solution, the system of equations
$$ \begin{pmatrix} 1 & 1 \\ e^{ka} & e^{-ka} \end{pmatrix} \begin{pmatrix} A \\ B \end{pmatrix} = 0 $$
must be degenerate (else the only solution is zero). Hence the determinant of the matrix must vanish; this is
$$ e^{-ka}-e^{ka}=0, $$
or $e^{2ka}=1$. Recalling Euler's formula, this occurs if and only if $2ka=2n\pi i $ for some integer $n$. Hence $k=\frac{n\pi i}{a}$. The condition at zero gives $y=2A\sinh{kx}$, and $\sinh{iz} = i\sin{z}$, so the eigenfunctions are proportional to $\sin{(n\pi x/a)}$, for $n \in \{ 1,2,3,\dotsc\}$. Certainly this looks plausible, since this satisfies the equation and boundary conditions.
Comment: can we not use the fact that $A=-B$ so we get $$Ae^ka+Be^{-ka}=0\implies 0=A(e^{-ka}-e^{ka})$$
Comment: It's the same thing, my way just has more emphasis on why the boundary conditions determine $k$, and not one of $A$ or $B$, for example. Either way is fine.
Comment: May I ask how you go from calculating k writing that the condition at zero gives  $y=2Asinhkx$
Comment: That's where one uses $A+B=0$ to note that $B=-A$. Or one can use the other boundary condition, which will give the same result.
Comment: Okay is an orthogonal relation for this problem $$\int sin(\frac{n\pi x}{a})-\int sin(\frac{n\pi x}{a}dx=0$$
Answer: I'll suggest a general method that separates the equations at the endpoints. This does not directly answer your question, but the method is worth knowing.
For a solution $y$ of the second order equation $y''+\lambda y$, there is no non-trivial solution with $y(0)=0=y'(0)$. So, by scaling $y$ if necessary, it must be a solution of
$$
                 y''+\lambda y = 0, \;\; y(0)=0,\;\; y'(0)=1,
$$
which has unique solution
$$
                 y_{\lambda}(x) = \frac{\sin(\sqrt{\lambda}x)}{\sqrt{\lambda}}.
$$
This version of the solution works for $\lambda=0$ by taking a limit:
$$
                 y_{0}=\lim_{\lambda\rightarrow 0}y_{\lambda}(x) = x.
$$
(This technique eliminates special cases because the limits always exist.)
Any non-trivial solution of the solution where $y(0)=0=y(a)$ must be a non-zero constant multiple of $y_{\lambda}$, which means that the only values of $\lambda$ for which there are non-trivial solutions must satisfy $y_{\lambda}(a)=0$. $\lambda=0$ does not work, which is easily checked because $y_0(x)=x$ does not vanish at $a$. The non-zero $\lambda$ must satisfy
$$
                \sin(\sqrt{\lambda}a) = 0 \\
             \implies \sqrt{\lambda}a = \pm \pi,\pm 2\pi,\pm 3\pi,\cdots \\
                 \implies \lambda = \frac{n^2\pi^2}{a^2},\;\; n=1,2,3,\cdots.
$$


Drupal 7, AJAX and browser history

Question: I have a website which is AJAX enabled for a great part.
My client now of course wants the browser buttons to behave as expected, which means the page should revert to the previous states when the 'back' button is pressed and so on.
I know there are solutions for this use case, the most interesting one being (seemingly) history_js and its fellow Statehandler module.
I didn't test it yet, because it seems to be heavily based on coding - which I could handle - but I wonder if there is a more elegant (mean : abstract) solution.
The following points are mandatory :

It must work with AJAX Views, including dynamic filters.
It must work with custom AJAX links.
It would be wonderful if it worked with popups (Colorbox style for example), but I think it's a lot to ask for so I could do without it.

What is your experience with AJAX browser history in Drupal 7 ? Any hint on the pitfalls you encountered would be very appreciated. A working solution or a good tutorial would be amazing.
Answer: For utilizing browser history and reload buttons with AJAX request, you can use the jquery plugin "jQuery Address"
http://www.asual.com/jquery/address/
Comment: Looks interesting, will give it a try when I'll have time. I upvote your answer, but be aware that just posting links is not considered a good enough answer here. Thanks for your contribution anyway.
Comment: @tekilatexee Did you get a chance to try this out?

Drupal 7, AJAX and browser history


How to retrieve information from a Django template

Question: I have a django template that calls a python methods but I can't seem to find a way for the python method to retrieve information from the template such as user input. Could anybody tell me how to do this?
Comment: Learn [The Forms API](https://docs.djangoproject.com/en/dev/ref/forms/api/#module-django.forms)
Comment: User input, just with HTTP requests... right?
Answer: I think you're under a misconception (A reasonably common one) that because you can use django variables in the html template, the template can "send" information back to django/the database.
Instead, try to get into the habit of thinking in terms of request/response. The user requests a web page, the django server builds up the response using content from the database and an html template (via the template language) and serves it to the user. If the response page has a form in it, that's not the "template" sending information back to the Django server, that's the response web page providing the user will tools to make ANOTHER request (this time a POST request).
The template is merely a generic container that you fill up with your dynamic content to build up the entire HTTP response.


What did John Cage mean by 'harmony' in his explanation to Arnold Schönberg?

Question: Source: John Cage, Silence: Lectures and Writings, p. 261 Bottom Left:

Five years later, when Schoenberg asked me
  whether I would devote my life to music, I said,
  "Of course." After I had been studying with him
  for two years, Schoenberg said, "In order to write
  music, you must have a feeling for harmony." I
  explained to him that I had no feeling for harmony. [Bold mine] He then said that I would always encounter an obstacle, that it would be as though I
  came to a wall through which I could not pass. I said, "In that case I will devote my life to beating
  my head against that wall."

I'm not sure which meaning of 'harmony' John Cage intended, and Cage's novel approach to harmony suggests his not intending to mean Western tonal music's harmony:

Western music is based on major and minor triads. The reason why these chords are so central is that they are consonant in terms of both fusion and lack of roughness. They fuse because they include the perfect fourth/fifth interval. They lack roughness because they lack major and minor second intervals. No other combination of three tones in the chromatic scale satisfies these criteria.
Comment: Even the likes of Schoenberg sometimes spout nonsense. Show me what Steve Reich's "clapping music" has to do with harmony, and I might change my mind about using the word "nonsense". There are musical traditions that have been around for millennia with no use of harmony (in the western sense of the word) whatever - e.g. classical Indian music.
Comment: I think you're a bit confused. When John Cage said he had no feeling for harmony, I believe he did mean he had no feeling for typical Western tonal harmony. In my opinion it was this disregard for it which led him to develop his own unique way of looking at harmony.
Answer: First let's consider that it is Schoenberg who asks the question and uses the word "harmony". In is book THEORY OF HARMONY he defines (pag.13) harmony as

"...the study of simultaneous sounds (chords) and of how they may be
  joined with respect to their architectonic, melodic, and rhythmic
  values and their significance, their weight relative to one another."

It's a pretty broad definition, but the insertion of the word "chord" seems to indicate that tonal harmony is what's on his mind (and it is, indeed, mostly what the book is about).
Now this is a relatively early work from Shoenberg (written in 1910, before he developed dodecaphony and all that), so he could have broadened the definition later on to include alternative non tonal systems. However, from what little I know about the theory of dodecaphony, the word "harmony" is not used to describe that system. Words like "system", or the preferred word by Shoenberg, "method" are used. Shoenberg defined dodecaphony as a

"Method of composing with twelve tones which are related only with
  one another" [Schoenberg, Arnold. 1975. As quoted in
  Wikipedia].

The word "harmony" does not enter the definition, which seems to indicate that he still associated the word "harmony" with classical tonal harmony.
It's also important to remember that for Shoenberg atonalism and dodecaphony were an evolution from tonal harmony, which remained an important theoretical basis to support the composer's efforts:

"Schoenberg viewed his development as a natural progression, and he
  did not deprecate his earlier works when he ventured into
  serialism." [Wikipedia]

Taking all this into consideration it seems to me that when asking the question in 1934 or 35, Shoenberg considered the meaning of "harmony" to be traditional tonal harmony. It seems reasonable that after two years studying with the master, there would be some common understanding of language and such critical concepts, so we can admit (even if it is Cage who is quoting Shoenberg some 20 odd years later) that in his answer Cage uses the word in the same sense.
To reinforce this view there's a very interesting paper by James Tenney, "John Cage and the Theory of Harmony" (1983). Tenney was a music theorist with a particular interest in the work of John Cage, so his saying is probably relevant in the interpretation of Cage's meaning.
In Tenney's view,

"...the very meaning of the word "harmony" has come to be so narrowly
  defined that it can only be thought of as applying to the materials
  and procedures of the diatonic/triadic tonal system of the last two or
  three centuries".

And according to him, Cage thought of harmony as being a constraint or barrier (the "wall" he himself talks about in the OP's original quote) that he should escape from:

"There were many such walls, but "harmony" — in its narrowest sense (the materials and procedures of traditional, tonal, textbook harmony)
  — was for Cage a particularly obstructive one:

[now quoting from Cage himself]

"Harmony, so-called, is a forced abstract vertical relation which blots out the spontaneous transmitting nature of each of the sounds
  forced into it. It is artificial and unrealistic. (1954)"

It seems that Tenney's view was also that when Caged used the word "harmony" he meant mainly "traditional, tonal, textbook harmony".

It seems that by (purposely?) not using the word "harmony" to describe different systems of composition, both Shoenberg and Cage want to make explicit the freedom from the rules of "traditional" harmony. However, whereas Shoenberg still considers "harmony" as a building block for learning and to evolve to other systems, Cage (as already commented by Craig Curtis) wants to discard it altogether.
BTW, Tenney's paper is rather interesting in his attempt to broaden the concept of harmony to cover different systems to organize pitch in music.

"The word ["harmony"] has a very long and interesting history,
  however, which suggests that it need not be so narrowly defined, and
  that the "continued evolution of the theory of harmony" might depend
  on — among other things — a broadening of our definition of
  "harmony."


Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154 VB.net

Question: I code in VB.net under Visual Studio 2008. I have this error and I don't understand why.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I use a DLL and I want to compile it in 64bit. I have the following code:
<code>Imports MetroProDAT_Library

Public Class Data
    Public attr As ZygoDataAttributes
    Public oData As ZygoDataFile

    Public Sub LoadData(ByVal FileName As String)
        Dim idx As Double
        Dim jdx As Double

        oData = New ZygoDataFile  '///this sentence bug
        attr = oData.Attribute
    End Sub
End Class
</code>
Comment: The COM DLL is almost certainly a 32bit DLL.  IF you app must remain 64bit, you will have to jump thru some hoops to get them to work together.  See this: http://www.scribd.com/doc/56629579/64-Bit-Insider-Volume-1-Issue-7
Comment: See this SO answer
[How to repair COM Exception error 80040154](http://stackoverflow.com/questions/7197506/how-to-repair-comexception-error-80040154)
Comment: Ok i will try . I think the problem is my library because in 32 bi it works well. I wanted to changed my dll , but is it normal that the path of my dll in visual studio is \Home\Desktop\P4\WindowsApplication3\obj\x64\Debug\Interop.MetroProDAT_Library.dll ?? Visual studio made a copy in a folder ?
Comment: It is works !! thant you !
Answer: it might be the dll file. do you have a specific dll files that needed to run the program ?
register it to the machine and test it again


Getting 404 error on MVC web-site

Question: I have an IIS7.5 web-site, on Windows Server 2008, with an ASP.NET MVC2 web-site deployed to it. The website was built in Visual Studio 2008, targeting .NET 3.5, and IIS 5.1 has been successfully configured to run it as well, for local testing.
We've installed the world's simplest MVC application (the one which is created when you create a new MVC2 project in Visual Studio), and we are getting 404s on any page we try and access - e.g.
<my_server>/Home/About will generate a 404.
I've asked this question on StackOverflow as well, but that was before I knew it was a server issue.
I have checked the following things:

There are 404 entries in the IIS log, corresponding to each request.
The application pool for the web-site is set to use the Integrated pipeline.
The "customErrors" mode is set to off.
.NET 3.5 SP1 is installed
ASP.NET MVC 2 is installed
I've used MVC Diagnostics to confirm all MVC DLLs are being found.
ASP.NET is enabled in IIS, which we've demonstrated by running the MVC Diagnostics page.
KB 2023146 did highlight that HTTP Redirection was off, so we've turned it on, but no joy.

Any ideas will be greatly appreciated!
Someone did suggest that there might be problems running it caused by Windows Server 2008 being 64-bit - does anyone know anything about this?
Answer: We finally nailed this issue by exporting the IIS configuration of a working server, and comparing it to ours.
It was a really obscure setting which had been changed from the default.
IIS ROOT → request Filtering → Filename Extensions Tab → Edit Feature Settings → Allow unlisted file name extensions
This should be ticked.
This can be set at the IIS level, or the site-level.
Answer: The first thing to confirm is that the extensionless URL hotfix has been applied: http://support.microsoft.com/kb/980368.
That should do the trick, but if not, does a simple test.aspx page work correctly?
Whether or not it's 32-bit or 64-bit won't make a difference for ASP.NET MVC. It's fully supported in both.

Getting 404 error on MVC web-site


Git Flow - Synchronizing two Unfinished Features

Question: We are working on one of our academic projects. Recently discovered Git Flow and are quite excited about it. But I have an issue which I would be glad if could be clarified.
Our group, divided into two sub-groups, works on multiple features. We just discovered that we need one unfinished feature to be used in another feature. That sure sounds crazy but this is the reason. I believe that we should have made features more atomic, but the division was made on entire namespaces. Then I went on coding frenzy and with some luck in simplifying the issue turbo boosted our side of project finishing our feature way ahead the schedule. The only feature left to work on for this semester depends on team B's product.
Just to be clear:

Team A - Feature X, Feature Z (requires some of Feature Y)
Team B - Feature Y
Team A is starting Feature Z, Team B hasn't finished feature Y.

Can Team A kind of checkout the code by Team B's Feature Y to continue with the project? Team B will update Feature Y in time, and Team A be able to fetch the updates as necessary.
Our current plan is to finish the current feature half way, factor the remainder work in to more atomic features and work on them. Then we (Team A) are hoping to rebase and keep ourselves up to date.
Any suggestion, apart from being a direct answer, would be great.
Answer:
Can Team A kind of checkout the code by Team B's Feature Y

If Team B releases an intermediate version of Y, then team A can track Y from its own repo.
See this answer as an example:
git flow feature track my-feature-branch

(based on git flow CLI, and git flow track)
Once you are tracking Y on team A's own repo, A can merge or rebase its work on top of Y.
Comment: Checked it out a little, seems to be what I want... Thanks a lot for the help! If I have any question I will put down a comment.


Criar um option selected jquery

Question: Já vi varias postagens sobre isso, mas nenhuma conseguiu me ajudar definitivamente.
Estou querendo colocar um option selected de forma dinâmica(dados do db).
obj.nome = [vitor,joao,carlos]

  dep_option += '<option name ='+obj.nome+'>'+obj.nome+'</option>';
  dep_select = '<select name="select_'+obj.nome+'">'+dep_option+'</select>';
  $('body').html(dep_select).show();

Desse modo como eu coloco o option joao como selected.
Agradeço a ajuda.
Comment: Em vez de vc usar `name` no `option`, deveria usar `value`, que seria o valor referente ao  respectivo `option`.
Answer: Não ficou muito claro qual seria a forma dinâmica, mas basta usar $("select").val("joao"), segue um código funcional usando seu exemplo:

var button = $("button")

button.on("click", function() {

  var obj = {};
  obj.nome = ["vitor", "joao", "carlos"];

  var dep_option = "";
  $.each(obj.nome, function(i) {
    dep_option += '<option name=' + obj.nome[i] + '>' + obj.nome[i] + '</option>';
  });

  var dep_select = '<select id="selecionar" name="select_' + obj.nome + '">' + dep_option + '</select>';
  dep_option += dep_option;

  $('body').html(dep_select).show();
  $('#selecionar').val('joao');

})

  <button>Montar Select!</button>

Comment: Não foi bem isso, mas ajudou a reformular minha ideia.
Obrigado.

Criar um option selected jquery


Continuous image of connected set is connected: Proof

Question: In De La Fuente's Mathematical Methods and Models for Economists, the following is said:

Let $f:X\to Y$ be a continuous mapping between two metric spaces. If C is a connected subset of $X$, then $f(C)$ is connected.

The proof goes as in Rudin's Principles, and I cannot understand exactly what Rudin also does not explain:

Suppose $f(C)$ is not connected. Then $f(C)=P\cup Q$, where $P$ and $Q$ are nonempty, separated subsets of $Y$, that is,
$clP\cap Q = \emptyset$ and $P\cap clQ = \emptyset$
Let $$ A = C\cap f^{-1}(P) \\ B = C\cap f^{-1}(Q) $$ and notice that then $$C = A\cup B$$ where neither $A$ nor $B$ is empty, and $$f(A)=P \\ f(B) = Q$$

The proof goes on, but this is where De La Fuente loses me. I can clearly see that $f(A)\subseteq P$, but not that $P\subseteq f(A)$. Any thoughts?
Thanks!
Comment: I have added ([tag:proof-explanation]) tag - see the [tag-info](https://math.stackexchange.com/tags/proof-explanation/info) - since your question seems to be about this specific proof (rather than asking for *any* proof of the fact mentioned in the title).
Answer: Let $p\in P$. Then as $P\subset f(C)$, we know that $f(c)=p$ for some $c\in C$. Can you go from there?
Comment: Yes! Thanks a lot!
Answer: The proof has to be properly aligned with the OP's definition of connectedness:
Definition: A subspace $C$ of a topological space $X$ is connected if and only if for any non-trivial partition $A \cup B$ of $C$,
$\qquad \overline{A} \cap B \ne \emptyset\; \text{ OR }\; A \cap \overline{B} \ne \emptyset$.
Proposition 1: A function $f: X \to Y$ is continuous $\text{ iff for every } A \subset X \text{, } f(\overline{A})\subseteq \overline{f(A)}$.
The above proposition and some general properties about sets and functions should be enough to construct the desired proof.


Weird sizing issues with h1 and span elements

Question: I have this code:

Windows Store
apps

and:
#windowsStoreApplications {
    float: right;
    width: 50%;

    font-size: 16pt;
    text-align: center;
    height: 182px;

    background-color: #9DCA87;
    border-top: 6px solid #AEDF66;
}

.smallSubText {
    font-size: 16pt;
}

As you can see, both the h1 and span are set to the same font-size - this is not how I want it but it's how I made it because I noticed that the font-sizes were not matching up to how they should be.
I made them both the same size to demonstrate that they are both the same size in code, but when you run the site and look at it - they're actually different sizes.
Is this due to some size weirdness with the h1 element?
Answer: If #windowsStoreApplications is a div, then you need to delclare a #windowsStoreApplications h1{} markup in your css and style the element with font-size:16px; there. You are not selecting the h1 element otherwise.
Comment: You mean 16pt (the same size as for the `span`), not 16px, right?
Comment: @JukkaK.Korpela You are correct. I am so used to px or em's that i didn't notice. Thanks.
Answer: Well first, if you havn't declared a font-size for your h1's (and the rest) the browser defaults will be implemented which vary in size.
Second, you should not be using pt for your size, you should be using px, em or %.
#windowsStoreApplications h1 {
font-size:16pt; /* or preffered unit */
}

Comment: Checkout http://stackoverflow.com/questions/348978/are-there-any-practical-reasons-to-use-em-instead-of-pt-font-size-units
Comment: Yes, you would typically have a print.css stylesheet that would do some general styling in a print-like format. I've never had to implement one as the newer browsers do a great job natively, but if your project has a reports/articles/products page or something, it's usefull.
Comment: Why not use point? We've always used pt :( Sigh. Then what is pt for?
Comment: "The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution." ~ css-tricks.com - Thanks @Chris.
Comment: But what if we want out whole site printed? Then we should use pt? But then if we do it all in pt anyway - we achieve the same result. What's the _real_ difference then?
Comment: I just had a heart attack. I changed everything to em (forgetting that I would need to use points to adjust), and everything became like Hulk lol.