How to create a dataset with conditional probability?

Question: Suppose that a certain disease ($D$) has a prevalence of $\dfrac3{1000}$. Also suppose that a certain symptom ($S$) has a prevalence (in the general population = people with that disease$ $D and people without that disease [probably with other disease, but it's not important]) of $\dfrac5{1000}$.
In a previous research, it was discovered that the conditional probability $P(S|D) = 30\%$ (the probability to have the symptom $S$, given the disease $D$ is $30\%$).
First question: Could be $P(S|D)$ interpreted as equivalent to the prevalence of the symptom $S$ in the group of people having the disease $D$?
Second question: I want to create in R a dataset, which shows that:
$$P(D|S) = \frac{P(S|D)P(D)} {P(S)}$$
With my fictional data, we can compute $P(D|S)=0.18$, that is interpreted in this way: given a patient with the symptom $S$, the probability that he has the disease $D$ is $18\%$.
How to do this? If I use simply the sample function, my dataset is lacking of the information that $P(S|D)=30\%$:
symptom <- sample(c("yes","no"), 1000, prob=c(0.005, 0.995), rep=T)
disease <- sample(c("yes","no"), 1000, prob=c(0.002, 0.998), rep=T)

So my question is: how to create a good dataset, including the conditional probability I desire?
EDIT: I posted the same question also on stackoverflow.com (https://stackoverflow.com/questions/7291935/how-to-create-a-dataset-with-conditional-probability), because, in my opinion, my question is inherited to the R language program, but also to statistical theory.
Comment: Common courtesy is to denote that you've cross-posted at another SE site. http://stackoverflow.com/questions/7291935/how-to-create-a-dataset-with-conditional-probability
Comment: I flagged your question on SO for migration. Please, don't cross-post!
Answer: You know the following marginal probabilities
                Symptom        Total
                Yes     No
Disease Yes      a       b     0.003
        No       c       d     0.997
Total           0.005   0.995  1.000

and that a/(a+b) = 0.3 so this becomes
                Symptom        Total
                Yes     No
Disease Yes     0.0009  0.0021 0.003
        No      0.0041  0.9929 0.997
Total           0.005   0.995  1.000

and indeed a/(a+c) = 0.18 as you stated.
So in R you could code something like
diseaserate <- 3/1000
symptomrate <- 5/1000
symptomgivendisease <- 0.3

status  <- sample(c("SYDY", "SNDY", "SYDN", "SNDN"), 1000,
            prob=c(diseaserate * symptomgivendisease,
                   diseaserate * (1-symptomgivendisease),
                   symptomrate - diseaserate * symptomgivendisease,
                   1 - symptomrate - diseaserate * (1-symptomgivendisease)),
            rep=TRUE)
symptom <- status %in% c("SYDY","SYDN")
disease <- status %in% c("SYDY","SNDY")

though you should note that 1000 is a small sample when one of the events has a probability of 0.0009 of happening.
Comment: Awesome solution, it works great! Now I can create a dataset showing what the Bayes formula can calculate. Thanks a lot!
Comment: Told you someone would come along with something more elegant ;)
Comment: @henry I would be really happy if you can give a look at my new question here: http://stats.stackexchange.com/questions/15202/create-a-dataset-with-condition-probability-2-2-symptoms. It is a generalization of this question, with 2 symptoms.
Answer: The table function returns a matrix-like object:
> symptom <- sample(c("yes","no"), 100, prob=c(0.2, 0.8), rep=TRUE)
> disease <- sample(c("yes","no"), 100, prob=c(0.2, 0.8), rep=TRUE)
> dataset <- data.frame(symptom, disease)
> dst_S_D <-with(dataset, table(symptom, disease))
> dst_S_D
       disease
symptom no yes
    no  65  13
    yes 17   5

So the Pr(D|S="yes") =
> probD_Sy <- dst_S_D[2, 2]/sum(dst_S_D[2, ] )
> probD_Sy
[1] 0.2272727

I changed the problem because the first time I ran it with your parameters, I got:
> dst_S_D <-with(dataset, table(symptom, disease)); dst_S_D
       disease
symptom   no  yes
    no  9954   22
    yes   24    0

And I thought a Pr(D|S="yes") of 0 was rather boring. If you are going to run this many times you should construct a function and use that function with the replicate function.
Here is a method of constructing a dataset that applies a different probability of disease in the symptomatic group that it 3 times higher than is used in the asymptomatic group:
symptom <- sample(c("yes","no"), 10000, prob=c(0.02, 0.98), rep=TRUE)
dataset <- data.frame(symptom, disease=NA)
dataset$disease[dataset$symptom == "yes"] <-
       sample(c("yes","no"), sum(dataset$symptom == "yes"), prob=c(0.15, 1-0.15), rep=TRUE)
dataset$disease[dataset$symptom == "no"] <-
        sample(c("yes","no"), sum(dataset$symptom == "no"), prob=c(0.05, 1-0.05), rep=TRUE)
 dst_S_D <-with(dataset, table(symptom, disease)); dst_S_D
#       disease
symptom   no  yes
    no  9284  509
    yes  176   31

Comment: Perfect, nice and elegant trick! I added some new information in my answer, to formalize better what I'm looking for.
Answer: I'd argue your question isn't really that heavily dependent on the R language, and more appropriate here, because - to be blunt - the generation of data like this is mostly a statistical task, rather than a programming one.
First Question: p(S|D) is the risk of having symptom S in a population with disease D. It can be directly comparable to the prevalence with certain caveats, like the symptom having no impact on disease duration. Consider the following example: One of the symptoms of SuperEbola is Instant Death, with p(Death | Super Ebola) = 0.99. Here, your prevalence of the symptom would actually be extremely low (indeed, 0.00) as no one you can sample with the disease has the symptom.
Second Question: I would back into this in a somewhat stepwise fashion. First, calculate the baseline risk of the symptom you'll need to get 0.15 in the whole population, taking into account that 0.03% of your population will be at higher rate. Then essentially generate two probabilities:

Risk of disease = 0.003
Risk of symptom = calculated baseline risk + relative increase due to disease * binary indicator of disease status

Then generate two uniform random numbers. If the first is less than 0.003, they've got the disease. That then gets fed into the risk calculation for the second, and if the random number for each individual is less than their risk, they've got the symptom.
This is sort of a plodding, inelegant way to do things, and its likely someone will come by with a far more efficient approach. But I find in simulation studies spelling each step out in the code, and keeping it as close to how I would see a data set in the real world is useful.
Comment: Thanks for the answer; the SuperEbola example is really educative and useful! The rest of your answer remains quite unclear, to me, especially when you say "calculate the baseline risk of the symptom you'll need to get 0.15 in the whole population, taking into account that 0.03% of your population will be at higher rate". How to compute this baseline risk?
Comment: Honestly, its a pain to do. If I were you, I'd change my example slightly - rather than asserting that the *overall* risk in the population is 0.15, I'd say the baseline risk in the non-diseased is, say, 0.15 or 0.10, then determine the increase in risk I want in the diseased and let the overall risk fall where it may, rather than trying to set it. It's considerably easier to code, though you will possibly not have numbers that are quite as clean at the end.
Answer: First question:
Yes of course that is almost the definition, although you will have some error associated with your sample size. i.e. This is only exactly correct at an infinite sample size.
Second question:
This is called Bayes Theorem, but I presume you already know that. Now given the information you have provided I get the probability of P(D|S) as 0.18 or 18%:
P(S|D)P(D)
----------
   P(S)

  0.3*(3/1000)
= ------------
    (5/1000)

= 0.18

Now unfortunately, I am not too familiar with R so can't really help you out with an exact program. But surely the quantities of people that fall into each group are quite easy to calculate:
For your 10000 sample set you need:

50 people with symptoms (population*P(S))
9 people should have symptoms and the disease (50*P(D|S))
21 people with the disease and no symptoms (population*P(D)=30 and we already have 9)

Which should make generating a suitable population fairly trivial.
Comment: Yes, the true value is 0.18, sorry for wrong typing. The second part of your answer is correct, but the problem is to create a dataset (in R) that really has 9 people with disease and symptom. The "sample" function correctly creates 50 and 30 "yes" for, respectively, symptom and disease; but it does not ensure that 9 people (out of 30) are also in the group of "yes-disease".
Comment: Again afraid you might need someone more familiar with R than myself to help you on the use of this sample function. However, you could always generate a much larger population and then randomly pick 10000 samples from that.


SDL and Xcode. Build and Run Error

Question: I have been going off of this tutorial http://www.noquarterarcade.com/xcode-sdl-development-setup
So, I have downloaded both the SDL Runtime Library and the SDL Development Library and put their content in the specified folders. I have made sure that have followed these steps correctly.
However, when I click build and run I get an error and 2 warning.
Error:
1) Command/Developer/usr/bin/gcc-4.2 failed with exit code 1
Build Try of project Try with configuration Debug
Ld build/Try.build/Debug/Try.build/Objects-normal/x86_64/Try normal x86_64
cd "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try"
setenv MACOSX_DEPLOYMENT_TARGET 10.6
/Developer/usr/bin/gcc-4.2 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk "-L/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" "-F/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" -F/Users/nickcarver/Library/Frameworks -F/Developer/SDKs/MacOSX10.6.sdk/Library/Frameworks -filelist "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/x86_64/Try.LinkFileList" -mmacosx-version-min=10.6 -framework SDL -framework Cocoa -o "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/x86_64/Try"

ld: warning: directory '/Users/nickcarver/Library/Frameworks' following -F not found
ld: framework not found SDL
collect2: ld returned 1 exit status
Command /Developer/usr/bin/gcc-4.2 failed with exit code 1

Ld build/Try.build/Debug/Try.build/Objects-normal/i386/Try normal i386
cd "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try"
setenv MACOSX_DEPLOYMENT_TARGET 10.4
/Developer/usr/bin/gcc-4.0 -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk "-L/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" "-F/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" -F/Users/nickcarver/Library/Frameworks -F/Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks -filelist "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/i386/Try.LinkFileList" -mmacosx-version-min=10.4 -framework SDL -framework Cocoa -o "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/i386/Try"

ld: warning: directory '/Users/nickcarver/Library/Frameworks' following -F not found

Warnings:
1) Directory'/Users/RustyShackleford/Library/Frameworks' following -F not found
it says this warning twice
Build Try of project Try with configuration Debug
Ld build/Try.build/Debug/Try.build/Objects-normal/x86_64/Try normal x86_64
cd "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try"
setenv MACOSX_DEPLOYMENT_TARGET 10.6
/Developer/usr/bin/gcc-4.2 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk "-L/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" "-F/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" -F/Users/nickcarver/Library/Frameworks -F/Developer/SDKs/MacOSX10.6.sdk/Library/Frameworks -filelist "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/x86_64/Try.LinkFileList" -mmacosx-version-min=10.6 -framework SDL -framework Cocoa -o "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/x86_64/Try"

ld: warning: directory '/Users/nickcarver/Library/Frameworks' following -F not found
ld: framework not found SDL
collect2: ld returned 1 exit status
Command /Developer/usr/bin/gcc-4.2 failed with exit code 1

Ld build/Try.build/Debug/Try.build/Objects-normal/i386/Try normal i386
cd "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try"
setenv MACOSX_DEPLOYMENT_TARGET 10.4
/Developer/usr/bin/gcc-4.0 -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk "-L/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" "-F/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Debug" -F/Users/nickcarver/Library/Frameworks -F/Developer/SDKs/MacOSX10.4u.sdk/Library/Frameworks -filelist "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/i386/Try.LinkFileList" -mmacosx-version-min=10.4 -framework SDL -framework Cocoa -o "/Users/nickcarver/Desktop/Lazy Foo Tutorials/Try/build/Try.build/Debug/Try.build/Objects-normal/i386/Try"

ld: warning: directory '/Users/nickcarver/Library/Frameworks' following -F not found

How do I do I fix this?
Comment: possible duplicate of [SDL Help. Xcode. Build and Run Error](http://stackoverflow.com/questions/5918932/sdl-help-xcode-build-and-run-error)
Comment: I did post this same question yesterday, but it did not have the information about Errors and Warnings that were necessary.

Im still looking for some help tho..
Comment: In that case, the expected behaviour is to edit the original question and make it clear that you've updated it with more information. See the [FAQ](http://stackoverflow.com/faq).
Answer: First of all, carefully check for dublicates.
Also, try changing the foundation template.

SDL and Xcode. Build and Run Error


How to Deploy Mule as a REST Service

Question: Hi I am working with Mule Studio and i am successfully running my flow in Mule Studio. I have certain issues related to implementation level since i have multiple flows in the one project.

How to deploy Mule as a REST Service with the existing flow.
If i am deploying my Mule as a REST Service what are the inputs i have to provide to make it run from the external HTTP Client based program.
When to use HTTP Client and when to use Mule Client. Which one fits where.
Comment: So you need to add a rest endpoint into a existing flow ?
Comment: nopes i know how to add REST endpoint but i want to deploy it as a stand alone service , While i am running it from Mule Studio its running , i want to create a Spring REST Service with standalone Mule Server runtime , based on that i am interested to know more about the points which i have mention in the questions.
Comment: When you say "stand alone service", do you mean as a Mule application running in the Mule Standalone container?
Answer: you can make use of RAML
1.create a RAML and generate the flows which internally referes your current flows

you can configure the Http details in generated flows
why you want to use http client and Mule client in your flows?

How to Deploy Mule as a REST Service


apache2 suexec destroy my day

Question: I have a puzzle with http suEXEC now.
It is a bit of frustration. Basically apache2 report weird lines in error.log
<code>[Fri Dec 18 11:29:57.385776 2020] [ssl:info] [pid 10944] AH01876: mod_ssl/2.4.38 compiled against Server: Apache/2.4.38, Library: OpenSSL/1.1.1d
[Fri Dec 18 11:29:57.385847 2020] [suexec:notice] [pid 10944] AH01232: suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec)

[ 2020-12-18 11:29:57.3873 10949/7fc39bfff700 age/Cor/CoreMain.cpp:532 ]: Signal received. Gracefully shutting down... (send signal 2 more time(s) to force shutdown)
[ 2020-12-18 11:29:57.3873 10954/7f5afc99e700 age/Ust/UstRouterMain.cpp:422 ]: Signal received. Gracefully shutting down... (send signal 2 more time(s) to force shutdown)
[ 2020-12-18 11:29:57.3873 10949/7fc3a8fba980 age/Cor/CoreMain.cpp:901 ]: Received command to shutdown gracefully. Waiting until all clients have disconnected...
[ 2020-12-18 11:29:57.3873 10954/7f5afca9d980 age/Ust/UstRouterMain.cpp:492 ]: Received command to shutdown gracefully. Waiting until all clients have disconnected...
[ 2020-12-18 11:29:57.3874 10954/7f5afc99e700 Ser/Server.h:464 ]: [UstRouter] Shutdown finished
[ 2020-12-18 11:29:57.3874 10954/7f5aeffff700 Ser/Server.h:817 ]: [UstRouterApiServer] Freed 0 spare client objects
[ 2020-12-18 11:29:57.3874 10954/7f5aeffff700 Ser/Server.h:464 ]: [UstRouterApiServer] Shutdown finished
[ 2020-12-18 11:29:57.3875 10949/7fc39b7fe700 Ser/Server.h:817 ]: [ServerThr.2] Freed 128 spare client objects
[ 2020-12-18 11:29:57.3875 10949/7fc39b7fe700 Ser/Server.h:464 ]: [ServerThr.2] Shutdown finished
[ 2020-12-18 11:29:57.3876 10949/7fc39affd700 Ser/Server.h:817 ]: [ServerThr.3] Freed 128 spare client objects
[ 2020-12-18 11:29:57.3876 10949/7fc39affd700 Ser/Server.h:464 ]: [ServerThr.3] Shutdown finished
[ 2020-12-18 11:29:57.3877 10949/7fc39a7fc700 Ser/Server.h:817 ]: [ServerThr.4] Freed 128 spare client objects
[ 2020-12-18 11:29:57.3877 10949/7fc39a7fc700 Ser/Server.h:464 ]: [ServerThr.4] Shutdown finished
[ 2020-12-18 11:29:57.3878 10949/7fc39bfff700 Ser/Server.h:817 ]: [ServerThr.1] Freed 128 spare client objects
[ 2020-12-18 11:29:57.3878 10949/7fc39bfff700 Ser/Server.h:464 ]: [ServerThr.1] Shutdown finished
[ 2020-12-18 11:29:57.3879 10949/7fc399ffb700 Ser/Server.h:817 ]: [ApiServer] Freed 0 spare client objects
[ 2020-12-18 11:29:57.3879 10949/7fc399ffb700 Ser/Server.h:464 ]: [ApiServer] Shutdown finished
</code>
And the starting sequence looks OK, however occasionally whatever suexec plays a role it doesn't load properly.
How can i trace it, or find it.
Answer: command
<code>a2dismod passanger
</code>
does the trick
Comment: A bit more explanation on *why* this is the solution wouldn't hurt.

apache2 suexec destroy my day


Get day of year from a string date in pandas dataframe

Question: I want to turn my date string into day of year... I try this code..
import pandas as pd
import datetime

data = pd.DataFrame()
data = pd.read_csv(xFilename, sep=",")

and get this DataFrame
Index Date        Tmin    Tmax
0   1950-01-02  -16.508 -2.096
1   1950-01-03  -6.769  0.875
2   1950-01-04  -1.795  8.859
3   1950-01-05  1.995   9.487
4   1950-01-06  -17.738 -9.766

I try this...
convert = lambda x: x.DatetimeIndex.dayofyear
data['Date'].map(convert)

with this error:
AttributeError: 'str' object has no attribute 'DatetimeIndex'

I expect to get new date to match 1950-01-02 = 2, 1950-01-03 = 3...
Thank for your help... and sorry Im new on python
Answer: I think need pass parameter parse_dates to read_csv and then call Series.dt.dayofyear:
data = pd.read_csv(xFilename, parse_dates=["Date"])
data['dayofyear'] = data['Date'].dt.dayofyear

Comment: Excellent! Exactly what I need,


Equivalence with measurable functions and spaces

Question: i have been reading Follands Real Analysis Book and i got stuck with one exercise. It says that if $\lambda(X)$ is finite  and $(X,M,\lambda)$ is a measure space and $(X, \overline{M}, \overline{\lambda})$ its completion. Suppose $f$ is bounded, then it is $\overline{M}$-mensurable iff theres exists sequences of $M$ simple mensurable functions ${\phi_n}$ and $ \psi_n $ such that $ \phi_n \leq f \leq \psi_n$ and $ \int \psi_n - \phi_n \leq 1/n$.
I think i can do one of the implications cause if there exists sequence of functions like that we will get by the dominated convergence theorem that $f$ will be $M-mensurable$ and so it will be $\overline{M} -mensurable$ and we can swap the limits with the integral. Is this correct ?? Or i need to complete it more??
But i have no idea how to do the other one, my idea was that if $f$ is mensurable in the extension the there exists simple functions that converge to $f$ and $-f$ but how do i know that these simple functions are $M-mensurable$?? , any help is welcomed.
Answer: If $f$ is bounded and $M-$ measurable there exist simple functions $g_n$ increasing to $f^{+}$ and simple functions $h_n$ decreasing to $f^{-}$. Hence $\phi_n \equiv g_n-h_n \leq f$ and $\int (f-\phi_n) \to 0$. By applying this to $-f$ we can find the $\psi_n$'s. Once you get $\int (\psi_n-\phi_n) \to 0$ you can go to a subseqeunce to get the inequality $\int (\psi_n-\phi_n) \leq \frac 1 n$ for all $n$.
Now suppose $f$ is bounded and $\overset {-}M$ measurable. There exists an $M-$ measurable function $g$ such that $f=g$ almost everywhere. Suppose $f(x)=g(x)$ for $x \notin E$   where $E$ has measure $0$. Suppose $-C<f(x)<C$ for all $x$. Now choose $\phi_n$ and $\psi_n$ as above with $f$ changed to $g$ and then  define $\Phi_n=\phi_n-I_E C,\Psi_n=\psi_n+I_E C$. Then  $\Phi_n$ and $\Psi_n$ are simple functions satisfying the required properties.
Comment: Yes that was my idea , but my question is when i find these sequence of simple functions they are defined in the completed measure how do i know that they are also going to work with respect to $M$? There could be sets where they are defined that arent in $M$ right?
Comment: @PedroSantos I have edited my answer
Comment: Ah yeah Thanks, yeah the sets are gonna have measure zero so those sets really arent gonna affect the integral , thanks !!


RDBMS-independent way to get table primary key?

Question: Let's assume we have Drupal instance with second database connection. Tables in that second database are shared between many systems and thus was not created using Drupal's schema functionality. How do I get the name of the primary key, in a universal way that doesn't dependent on the RDBMS? Is there a way that will be equally good for all databases?
For MySQL I can use db_query and:
SHOW INDEX FROM {table} WHERE Key_name = "PRIMARY"

and for SQL-92 compatible ones:
SELECT pk.TABLE_NAME, c.COLUMN_NAME primary_key
  FROM information_schema.table_constraints pk
  JOIN information_schema.key_column_usage c
    ON c.table_name = pk.table_name
   AND c.constraint_name = pk.constraint_name
 WHERE constraint_type = 'primary key'

Thanks to T I's answer on stackoverflow.
What happens with Oracle or Apache Derby? I know I can find specific solutions, but I wonder if there is a Drupal way. I couldn't find one outside schema.
Answer: For non-Drupal tables
I don't think there is a cross-db drupal way to do this currently.
It would have to be added to the database schema class for each database type.
For example, see the mysql database schema class and look at something like addIndex.
Something similar could be done for showIndex().
If it is added for all the different database handlers, it would then be able to be safely used.
Then a database API function would have to be added for easy calling.
For example you would need a db_show_index() function in database.inc like db_add_index().
For Drupal defined tables
You can use drupal_get_schema() and get the schema for a table; then, get what you need from that. It will return a schema as defined in hook_schema().
You might also be interested in some of the other schema API functions.
The schema will only be what was defined in hook_schema though. It won't pick up anything that has been added or changed outside of that.
Comment: It is not an answer to my question. I'm asking specifically about tables **not** defined inside Drupal.
Comment: Oops, sorry. Fixing my answer.
Comment: No problem. Added emphasis in question to make it stand out.
Comment: I don't like your answer, because I don't like the facts it shows. But it seems I have no choice but appreciate comprehensiveness and just accept it. And hope in 8 it'll be different.
Comment: Yeah, It's probably not going to be fast/easy to get into drupal 7 at this stage. It would be relatively easy to get it into Drupal 8 though. There are probably other admin statements that are missing too.
Comment: So, which of us writes feature request?
Comment: Feature request created: http://drupal.org/node/2006800
Comment: Nice one, that saves me remembering to make on :)
Comment: I have this funny feeling it will be happily ignored, but at least it will not be a case of "nobody told us!".


Mudar os ícones do menu Navigation Drawer

Question: Gostaria de saber como faço para trocar esses ícones:

Eu achei a tela, mas quando clico não me mostra o caminho para fazer a alteração e sim só cores em RGBA :
Answer: Percebi que você está usando o Padrão Navigation Drawer, então para mudar os ícones e personalizar como você quiser, basta ir na pasta menu e no arquivo activity_main_drawer.xml e fazer as mudanças como quiser.
Veja um exemplo:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:title="@string/menu1">
    <menu>
        <item
            android:icon="@drawable/ic_check_box"
            android:id="@+id/nav_um"
            android:title="@string/categoria1" />
        <item
            android:icon="@drawable/ic_check_box"
            android:id="@+id/nav_dois"
            android:title="@string/categoria2" />
        <item
            android:icon="@drawable/ic_check_box"
            android:id="@+id/nav_tres"
            android:title="@string/categoria3" />
        <item
            android:icon="@drawable/ic_check_box"
            android:id="@+id/nav_quatro"
            android:title="@string/categoria4" />
        <item
            android:icon="@drawable/ic_check_box"
            android:id="@+id/nav_cinco"
            android:title="@string/categoria5" />
        <item
            android:icon="@drawable/ic_check_box"
            android:id="@+id/nav_seis"
            android:title="@string/categoria6" />
    </menu>
    </item>
        <item android:title="@string/menu2">
        <menu>
            <item
                android:icon="@drawable/ic_check_box"
                android:id="@+id/nav_sete"
                android:title="@string/categoria7" />
            <item
                android:icon="@drawable/ic_check_box"
                android:id="@+id/nav_oito"
                android:title="@string/categoria8" />
            <item
                android:icon="@drawable/ic_check_box"
                android:id="@+id/nav_nove"
                android:title="@string/categoria9" />
            <item
                android:icon="@drawable/ic_check_box"
                android:id="@+id/nav_dez"
                android:title="@string/categoria10" />
        </menu>
    </item>
    <item android:title="@string/menu3">
        <menu>
            <item
                android:id="@+id/nav_sobre"
                android:icon="@drawable/ic_storage_24dp"
                android:title="@string/menusobre" />
            <item
                android:id="@+id/nav_sair"
                android:icon="@drawable/ic_clear_24dp"
                android:title="@string/menusair" />
        </menu>
    </item>

</menu>

Perceba que a IDE Android Studio oferece uma ferramenta muito útil, que é o Vector Asset para você criar um ícone personalizado, para fazer isso basta clicar com o botão direito em cima da pasta drawable > New > Vector Asset

Veja que acima o novo ícone está na pasta drawable, então basta agora você editar seu arquivo activity_main_drawer.xml, dessa maneira:
<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">

        <item android:title="@string/menu1">
        <menu>
            <item
                android:icon="@drawable/ic_3d_rotation_black_24dp"
                android:id="@+id/nav_um"
                android:title="@string/categoria1" />

Espero ter ajudado.
Comment: Cara, muito obrigado. Você me ajudou muito. Agora sim. Valeu mesmo.


Free software to analyse voice pitch

Question: I'd like to analyse recordings to see when and how much out of tune I sing, in order to practice my singing. I'm aware of expensive solutions such as Melodyne, but is there any free way to do that?
Comment: I'm using Windows.
Comment: Hi Anna. Unfortunately, asking for software recommendations is off-topic here. You may be able to ask on the [Software Recs SE](http://softwarerecs.stackexchange.com/) if you can format your question to [their standards](http://meta.softwarerecs.stackexchange.com/questions/336/what-is-required-for-a-question-to-contain-enough-information). To find out more about this site [take the tour](http://music.stackexchange.com/tour) and read the [FAQ](http://music.stackexchange.com/help/on-topic).
Answer: You can download a choice of free tuner apps for any computer, tablet or phone.
I should warn you - it will be interesting to sing a slow scale and see if you're on pitch.  You'll get less useful information about real-life singing.   So tune your ear in by singing sustained notes into the meter, then LISTEN to your recorded voice to criticise it.

Free software to analyse voice pitch


Solaris/Unix equivalent of Event Log

Question: What is the unix equivalent of the Windows Event Log - the tool that logs all processes that start and stop.
Need not be exact - with the whole GUI and everything. Anything close would do.
Answer: This is different for Solaris/Linux:

Solaris 10: /var/svc/log/svc.startd.log
Linux: /var/log/syslog or /var/log/messages*

*Although most daemons have their own logfiles in /var/log/daemonname/ for example.
Answer: the /var/log directory is where almost all logs end up. There are graphical tools around to read them, though almost all are admin-friendly text.
Answer: There is auditd which included many informations like ... who execute what.
Also there is syslogd / syslog-ng / rsyslog whcih is being used to monitor syslog event and parse / make actions based on some rules (These rules usually are located on /etc/rsyslog.d or /etc/rsyslog.conf {similar /etc/auditd.conf}).
For GUI you could use logzilla or splunk as free frameworks. (Of course there are many many others)
Answer: auditd would do your audits (but you will need to configure this).  Additionally your "equivilent" of Event Log would ultimately be syslog-ng, which replaces most syslog on most Linux/Unix systems.  Furthermore, there is a utility called logrotate on Linux systems that allows you to rotate out your log files on a time/size basis, highly configurable.

Solaris/Unix equivalent of Event Log


Pooled Covariance Matrix with very different amount of samples per class

Question: I have a dataset with 10 classes, and want to estimate the covariance. It turns out that due to numerical stabilitiy, it is much better to use a pooled covariance matrix. Suppose I have $N$ samples per class. Then
$$S_{\mathrm{pooled}} = \frac{1}{10 * N} \sum_{i=1}^{10} \sum_{j=1}^N (x_j - \mathrm{mean}(x_j)) (x_j - \mathrm{mean}(x_j))'$$
I would also like to perform LDA (for dimensionality reduction and later classification) on the dataset, and the computation of the Within-Class Scatter Matrix $S_W$ is almost the same upto the scaling factor.
I do have a very unbalanced classes - quite different number of samples per class. For example for class 1, I have only $100$ samples whereas for class 4 I have $5000$ samples!
Let $N_1, N_2, ... N_{10}$ denote the amount of samples for each class. According to https://en.wikipedia.org/wiki/Pooled_variance, one computes as
$$S_{\mathrm{pooled}} = \frac{1}{N_1 + N_2 + ... N_{10} - 10} \sum_{i=1}^{10} \sum_{j=1}^{N_i} (x_j - \mathrm{mean}(x_j)) (x_j - \mathrm{mean}(x_j))'$$
For my data set this gives not a good estimation of the covariance matrix. What did work was to artifically equalize the amount of samples per class by re-using data, and then estimating the covariance by the first equation. For example for class 1, I artifically increased the number of samples by re-using the 100 samples 50 times to get an amount of 5000 samples for this class, i.e. adding the same data again and again. This seems to remove an apparent bias.
It works quite well, but I have no mathematical explanation or intuition why???
Comment: The upper limit of the inner sum in the second equation is $N_i$, right?
Comment: indeed, thx for spotting. fixed that
Comment: The usual formula for the pooled covariance matrix is the weighted averaged matrix with their degrees of freedom (the "n-1"s) being the weights. But you are in right to invite other weights than that, for example equal weights (then the pooled matrix will be the simple average of the matrices).
Answer: In this kind of analysis you need to be clearer on what covariance matrix you are actually trying to estimate.  (You refer to estimating "the covariance", but the covariance of what with what?)  I am going to assume that "the covariance" you are trying to estimate is the covariance matrix for the vector of deviations of each output vector from the true mean for that category.  This can be framed by writing your model as a standard multivariate regression model, with error vectors representing the deviation of each output from the true mean for the category.  This framework will be used to elucidate the derivation of the pooled covariance estimator, and the conditions under which this is a reasonable estimator.

Where does the pooled covariance estimator come from: Consider a multivariate linear regression model for a response vector $\mathbf{Y}_i$ where we have a single categorical variable $z =1,...,m$ (with $m$ categories) and homoscedastic errors.  We can write the multivariate regression model as:
$$\mathbf{Y}_i = \sum_{k=1}^{m} \boldsymbol{\beta}_k \cdot \mathbb{I}(z_i=k) + \boldsymbol{\varepsilon}_i \quad \quad \quad
\boldsymbol{\varepsilon}_1, ... , \boldsymbol{\varepsilon}_n \sim \text{IID N}(\mathbf{0}, \boldsymbol{\Sigma}).$$
It is important to stress here that this model assumes homoscedastic errors, which means that we assume that the true covariance matrix of the error terms in each of the categories is the same.  We will soon see that this is a crucial assumption for the use of the pooled covariance estimator.
Without loss of generality, suppose that we have $N_1,...,N_m$ values in each of the respective categories, leading to corresponding response means $\bar{\mathbf{y}}_1, ..., \bar{\mathbf{y}}_m$.  It is simple to show that OLS estimation leads to the following coefficient estimators and corresponding residuals:
$$\hat{\boldsymbol{\beta}}_k = \bar{\mathbf{y}}_k \quad \quad \quad \quad \quad
\mathbf{r}_i = \mathbf{y}_i - \bar{\mathbf{y}}_{z_i}.$$
For the next step we will define $\mathbf{y}_{k,i}$ to be the $i$th response vector in the $k$th category.  Using this notation, the unbiased estimator of the covariance matrix of the error vector is:
$$\begin{equation} \begin{aligned}
\hat{\mathbf{\Sigma}}
&= \frac{1}{N-m} \sum_{i=1}^n \mathbf{r}_i \mathbf{r}_i^\text{T} \\[6pt]
&= \frac{1}{N-m} \sum_{i=1}^n (\mathbf{y}_i - \bar{\mathbf{y}}_{z_i}) (\mathbf{y}_i - \bar{\mathbf{y}}_{z_i})^\text{T} \\[6pt]
&= \frac{1}{N-m} \sum_{k=1}^m \sum_{i=1}^{N_i} (\mathbf{y}_{k,i} - \bar{\mathbf{y}}_k) (\mathbf{y}_{k,i} - \bar{\mathbf{y}}_{z_i})^\text{T} \\[6pt]
&= \frac{\sum_{k=1}^m \sum_{i=1}^{N_i} (\mathbf{y}_{k,i} - \bar{\mathbf{y}}_k) (\mathbf{y}_{k,i} - \bar{\mathbf{y}}_{z_i})^\text{T}}{\sum_{k=1}^m (N_k -1) } \\[6pt]
&= \hat{\mathbf{\Sigma}}_\text{Pooled}. \\[6pt]
\end{aligned} \end{equation}$$
We can see here that, in the case of OLS estimation, the corresponding estimator of the covariance of the error vector is equivalent to the pooled covariance estimator.  That is, this form of estimator arises as a natural unbiased estimator in the case where the output data is treated as coming from a standard multivariate regression based on an observed categorical variable, with homoscedastic error terms.

When is this a good/bad estimator: Since the pooled covariance estimator arises from standard OLS estimation under a model with homoscedastic errors, it should not be surprising that it is generally a good estimator in cases where this model form is appropriate, and a bad estimator in cases where this model form is inappropriate.  In particular, the legitimacy of the pooled covariance estimator hinges on the assumption of homoscedastic error terms, which is equivalent to assuming that the true covariance matrix of the error terms in each of the categories is the same.
If the true covariance matrices for the error terms in difference categories are substantially different then it should not be surprising that the above estimator will be a poor estimator of the assumed common covariance matrix.  Firstly, it means that you are attempting to estimate a single covariance matrix that does not in fact exist (i.e., there is not really a common covariance matrix across categories to begin with), and secondly, you are using OLS estimation that is generally poor in cases of serious heteroskedasticity.
In such cases it is best to revise your model to allow for heteroskedasticity and then use estimation techniques that are appropriate to this.  That might include some parametric specification of a heteroskedastic weighting structure (and corresponding estimation using WLS) or it might mean using basic sample estimates of the covariance across each of the categories, and not attempting to aggregate them.

Issues with your problem: In your problem you have $m=10$ categories, which is not many, but you have noted that they are very unbalanced.  In your description of your problem you way that you are estimating "the covariance" and that you have compared the pooled covariance estimator to "the covariance" and found it performed poorly.  Unfortunately, it is unclear exactly what covariance you are seeking to estimate, and it what covariance matrix you are comparing the pooled estimator to.
To improve your analysis, I would suggest that you begin by making a clearer specification of exactly what covariance you are trying to estimate, and what (if any) assumptions about the variance across groups is reasonable with this data.  I hope the above exposition assists you in understanding the derivation of the pooled covariance estimator and the assumptions behind this.


ImportError with flask_wtf on Raspberry PI 3

Question: first of all pls excuse my bad english skills ^^
My problem looks very simple to solve but I cant get flask_wtf running on my Raspberry Pi 3. I want to create a form with Flask-WTF but i am not able to import it.
I first installed it with
sudo pip install Flask-WTF

When I import the module
from flask_wtf import FlaskForm

and run the program I get this:
ImportError: No module named 'flask_wtf'

If I try to install it again, I get:
Requirement already satisfied: Flask-WTF in /usr/local/lib/python2.7/dist-packages

Thanks in advance!
Comment: Not enough information. Where is the rest of your project? Are you using a virtualenv? If not, why not? Why are you installing with sudo?
Comment: Check [here](https://stackoverflow.com/a/48781438/8928024) how to solve this. Tip: if you want to reinstall something the hard-way... remove the DL in pkgs and installed folder from site-packages.
Answer: Okay I got a solution:
I don't know why pip installs this libary into the outdated python 2.7 directorys by default. But with pip3 it is possible to install it to python 3.

sudo pip3 install Flask-WTF


O javascript não esta funcionando no django

Question: ja tentei de todas as formas, mas não consigo fazer o JS funcionar.
login.js:
$('.message a').click(function(){
   $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});

login.html;
{% load static %}

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="{% static 'gestao_clientes/css/login.css' %}" media="screen" />

        <form class="register-form">
          <input type="text" placeholder="name"/>
          <input type="password" placeholder="password"/>
          <input type="text" placeholder="email address"/>
          <button>create</button>

Already registered? Sign In

        </form>
        <form class="login-form">
          <input type="text" placeholder="username"/>
          <input type="password" placeholder="password"/>
          <button>login</button>

Not registered? Create an account

        </form>

Já tentei:
- com e sem o type="text/javascript"

também: src="gestao_clientes/js/login.js"

Meu diretório está da seguinte forma:

A parte de settings do meu projeto está assim:
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'rwn)otj+b3_nt6u(0rw^n9bw^yhd-0!h!3xtx$bwsa1%7hdv(q'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'clientes',
    'login',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'gestao_clientes.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'gestao_clientes.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS =[
    'estaticos',
]

MEDIA_URL = '/media/'

MEDIA_ROOT = 'media'

LOGIN_URL = ''

LOGIN_REDIRECT_URL = 'person_list'

A pagina de login e cadastro será a primeria pagina do projeto,
e gostaria que ficasse de acordo com essa: https://codepen.io/colorlib/pen/rxddKy
Porém quando clico em *create an account" não abre para inserir os outros dados.
Obrigado pela ajuda, sou iniciante nessa parte :)
Comment: Não vejo onde estás a carregar o jQuery...
Comment: é necessário? Ainda não sei sobre j'Query
Comment: Estás a utilizar jQuery, tens de importar no teu login.html;
Comment: Descarrega jQuery e coloca numa pasta na tua app, e adicionas a linha
Comment: Ok, vou tentar!
Answer: Explicando melhor, descarregas o jQuery e colocas na pasta de templates na tua app e colocas assim.
login.html
{% load static %}

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="{% static 'gestao_clientes/css/login.css' %}" media="screen" />

        <form class="register-form">
          <input type="text" placeholder="name"/>
          <input type="password" placeholder="password"/>
          <input type="text" placeholder="email address"/>
          <button>create</button>

Already registered? Sign In

        </form>
        <form class="login-form">
          <input type="text" placeholder="username"/>
          <input type="password" placeholder="password"/>
          <button>login</button>

Not registered? Create an account

        </form>

login.js
$(document).ready(function(){
  $('.message a').click(function(){
     $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
  });
});

Comment: Fiz isso mas não deu certo, continuou a mesma coisa
Comment: Atenção que tens de colocar o caminho correto para o teu ficheiro, eu coloquei main/vendor/jquery/...file, tens colocar para o teu caso e para a tua diretoria correta, eu testei seu código com jQuery e funcionou.
Comment: No seu teste o **Create an account** funcionou normal?
Já mudei o diretório mas mesmo assim não está funcionando
Comment: Partilha no github seu projeto e eu analiso
Comment: Já editei o código de forma que funciona, só estou procurando perceber o que tens mal ao importar o teu login.js ou o que está errado que este não funciona.
Comment: Agora sim, podes tcorrigir o teu código do login.js, faltava $(document).ready(function().
Comment: Muito obrigado!! Agradeço demais!! :)))


Is it possible to make a shorter representation for an equation?

Question: I have an equation as follows:
$$
f_{n,k_1,1}=
\begin{cases}
0,&\text{$k_1>n_1,$ or $n-k_1>n_2$}\\
\frac{\binom{n_1}{k_1}\binom{n_2}{n-k_1}}{\binom{n_1+n_2}{n}}, & \text{otherwise}
\end{cases}
$$
And
$$
f_{n,k_1,2}=
\begin{cases}
0,&\text{$k_1>n_2,$ or $n-k_1>n_1$}\\
\frac{\binom{n_2}{k_1}\binom{n_1}{n-k_1}}{\binom{n_1+n_2}{n}}, & \text{otherwise}
\end{cases}
$$
The different between $f_{n,k_1,1}, f_{n,k_1,2}$ is that just changes position of $n_1,n_2$ in the bionominal term. Hence, I want to make $f_{n,k_1,1}, f_{n,k_1,2}$ more shorter as
$$
f_{n,k_1,i}=
\begin{cases}
...\\
...
\end{cases}
$$
where $i={1,2}$. Is it possible to make it?
Answer: Well, you could say
$$f_{n,k_1,i} = \begin{cases}0, & k_1>n_i \text{ or } n-k_1 > n_{\bar i}\\
\displaystyle{\frac{{n_i\choose k_1}{n_{\bar i}\choose n-k_1}}{{n_1+n_2\choose n}}},& \text{otherwise} \end{cases}$$
and explain that $\bar 1=2$ and $\bar 2=1$.
Comment: but your bionominal term does not change and the invert way look so complex
Comment: @user2938494 It does now.


Induce measure between topological spaces.

Question: Let $X$ and $Y$ be topological spaces, suppose that the function $f:X\rightarrow  Y$ is a continuous surjection. Let $\mu$ be a regular measure on $X$, and $M_X$ the set of $\mu$-measurable sets in $X$. We can induce a measure on $Y$ define in the $\sigma$-algebra $M_Y=\{A\subset Y: f^{-1}(A)\in M_X\}$ as
$$\nu(A)=\mu(f^{-1}[A])$$
What conditions do we have to impose in order that the measure $\nu$ be regular?
I supposed that $\mu$ were regular but I got nothing.
Any clue?
Comment: Are there some particular conditions under which you want this to be true?
Comment: I know it is true if X is a string space with a Bernoulli measure,  Y is an associate self similar set and f is a kind of projection. But I don't know why is this true, I think is a more general fact that does not depend so strongly on the nature of X, Y and f. Maybe, it is enough if f is a quotient map or something like that (by the way in the example I mentioned f is indeed a closed map).
Comment: Different authors use different def'ns of regular measure. Is there one def'n you have in mind?
Answer: Let $A\in M_Y$. Then $$\nu(A)=\mu\big(f^{-1}(A)\big)=\sup\big\{\mu(K):K\subseteq f^{-1}(A),K \text{ compact}\big\},$$
since $\mu$ is regular. Now for $K\subseteq f^{-1}(A)$ with $K$ compact, $f(K)\subseteq A$ is compact too and $K\subseteq f^{-1}\big(f(K)\big)$. So $\nu\big(f(K)\big)=\mu\Big(f^{-1}\big(f(K)\big)\Big)\geq\mu(K)$ and $\nu$ is regular.


$y_t+-\epsilon .y_{xx}+ M.y_x=0\, ;(x,t) \in (0,1)\times(0,T)$ Boundary layers

Question: I was reading an article about pertubation in advection-transport equations, nad so they have defined the following equation with the perturbation ($\epsilon). $
$$y_t+-\epsilon .y_{xx}+ M.y_x=0\, ;(x,t) \in (0,1)\times(0,T)$$
$$y(0,t)=v(t), \text{if} \, M>0 \, ;t\in (0,T)$$
$$y(1,t)=0 \,\text{if}\,M<0 \, ;t\in (0,T)$$
$$y(x,0)=y_0(x) \, ; x\in (0,1)$$
And they took the case of$\epsilon=0 $, we will get the transport equation.
$$y_t+M.y_x=0\, ;(x,t) \in (0,1)\times(0,T)$$
$$y(0,t)=v(t), \text{if} \, M>0 \, ;t\in (0,T)$$
$$y(1,t)=0 \,\text{if}\,M<0 \, ;t\in (0,T)$$
$$y(x,0)=y_0(x) \, ; x\in (0,1)$$
and said that we have two boundary layers :
1/ In $x=1$ of size $O(\epsilon)$
2/ In the characterestic $\{(x,t)\in(0,1)\times (0,T): x-M.t=0\}$ of size $O(\sqrt{\epsilon})$
And I did not get how they concluded these results.
Comment: The system needs another boundary condition. (Or two more if $M=0$).
Comment: @David Well it's what I ve found in the article ; https://arxiv.org/pdf/1904.12669.pdf ; And if you can tell me how in general do we find those boudary layers.
Comment: In that article, the general equation (equation (1)) with nonzero $\epsilon$ has both boundary conditions, there is no dependence on $M$. It is only the weak formulation (equation (2)) with $\epsilon=0$ where there is only one boundary condition (and is chosen based on the sign of $M$).
Comment: @David yes, I understand, but how did they find the boundary layers ? because we need to solve equation and see where we might have a problem. and in this case why the problem is in the characterestion $\{(x,t) ; x-Mt=0\}$ and $x=1$
Answer: This is a partial answer, the details are in the linked paper, and references therein, I'm not going to attempt to rewrite it.
With $\epsilon=0$ the equation is order 1 in space, so can't satisfy 2 general boundary conditions. To find the location/size of the boundary layer, you can rescale $\eta=(x-x_0)/\epsilon^\alpha$ to give
$$ y_t-\epsilon^{1-2\alpha}y_{\eta\eta}+\epsilon^{-\alpha}My_\eta=0 $$
and so if $\alpha=1$ you have a dominant balance, so there is a boundary layer width $O(\epsilon)$.
If $M>1$ the boundary layer must be at $x_0=1$, and if $M<0$ it will be at $x_0=0$. The paper you linked to does go through these calculations in limited detail for the $M>0$ case.
Section 2 of the paper gives some more details about the different substitutions.
Also see this answer for general information about finding the location/width of boundary layers.
Comment: Exactly, when $\epsilon=0$ you can only satisfy one boundary condition (unless you get lucky and the other one is satisfied by chance, that's what I mean by general). The actual boundary layer you will satisfy depends on $M$, at the other end of the domain will be a boundary layer.
Comment: My second paragraph gives the rescaled equations for a boundary layer of width $\epsilon^\alpha$, then dominant balance tells us that $\alpha=1$. If these concepts are unfamiliar to you, I suggest studying boundary layer theory from a book before coming back to this particular equation.
Comment: 2 general boundary conditions ? which ones ?, because I think it doesn't satify only to $y(1,t)=0$ because transport equation, we only have initial condition, and one boundary condition for $x=0$. Correct me if I'm wrong.
Comment: Yes, well I'm having difficulties in determining boundary layers (exactly) and their length. in this case the article (page 3), said that we have boundary layers at $x=1$ (I agree because the boundary coundition is not satisfied) but how the length it's $\epsilon$ and why the characterestic $\{x-Mt=0\}$ is a layer of size $\sqrt{\epsilon}$


Summarise rows in dataframe by two columns

Question: I have this data frame called Worldwhich shows the following:
City           Year           Income           Tourist
London         2008             50               100
NY             2009             75               250
Paris          2010             45               340
Dubai          2008             32               240
London         2011             50               140
Abu Dhabi      2009             60               120
Paris          2009             70               140
NY             2007             50               150
Tokyo          2008             45               150
Dubai          2010             40               480
#With 207 more rows

I want to summarise each rows so that every city shows the total income and tourists for all the years. So I want to find a code where City and Years are matched and then summarised so that every city just have one row.
Something like this:
City          Income            Tourist
London         1051              5040
NY             1547              5432
Paris          2600              4321
Dubai          3222              5312
Abu Dhabi      3100              7654
Tokyo          2404              4321
#With 40 more rows

After the research I've done n_distinct and group_by should be used.
Comment: You're on the right lines.  What did you try and why didn't it work?
Comment: "My tibble looks strange" is equally uninformative.  So we know `n()` and `count()` don't give you what you want.  Have you tried `sum()` yet?  [This post](https://stackoverflow.com/help/minimal-reproducible-example) will help you ask a great question.
Comment: ```group_by(City) %>%
summarise(count = n_distinct(Year))```
Comment: However it doesn't work for me. @Limey
Comment: `count` counts rows.  `sum` sums values.  Keep at it.  Bear in mind that "it didn't work" isn't very informative.  In what way didn't it work?  Did you get an error message?  Did you get output that didn't meet your expectation?  We need clarity.
Comment: My tibble unfortunately looks strange. Count just shows how many years there are n says how many times the City are matching with a year. Hmm. @Limey
Comment: I suppose I need to mention ```Income```and ```Tourist``` in the code so it will be included in the tibble.
Comment: Thanks for your advice @Limey . I'll try to solve my task and then post an answer in this thread.
Answer: Base R solution:
You can use the sapply() function to iterate over cities.

the first argument will be a vector of unique cities
we then write our function that select all the rows (years) of each city and returns the "Income" and "Tourist" columns
Sum the columns values with colSums() function
Transpose the output using the t() function.

t( sapply( unique( World$City ),function(CITY) colSums(World[World$City==CITY,c("Income","Tourist")] ) ) )

Solution with R's data.table package:

Make sure your object is of type data.table.
in the j part of the bracket (the do part):
you can provide names to the wanted columns ("Income="),
and specify the wanted output ("sum(Income)").
To group the cities, add a by argument to the data.table object.

World[,.(Income=sum(Income),Tourist=sum(Tourist)),by=City]

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: yes, you can use group_by and summarise function.
world %>% group_by(City) %>% summarise(across(c(Income,Tourist), sum))

you can also add Year in the group by function.
world %>% group_by(City,Year) %>% summarise(across(c(Income,Tourist), sum))


read text file content and insert it into a mysql database

Question: Good day . I've the following code which i'm trying to make work . I have to read the content of a text file , which contains questions and save it to the database testsystem .
The main problem that i'm facing is that it's not inserted in the database. and i'm not sure whether it is reading the textfile or not.
any help will be glady appreciated
JFrame and main
public class StudentTestSystems {

    public static void main(String[] args) {

        try {

            Lecturer panel = new Lecturer();

            panel.setVisible(true);
            panel.setLocationRelativeTo(null);
            panel.setResizable(false);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Lecturer class
public class Lecturer extends JFrame implements ActionListener {

    Font font = null;
    private JTextField fileField;
    private JButton uploadBtn;
    private JLabel message;
    private JPanel panel;

    public Lecturer() {
        super("LECTURE MENU");

        this.setSize(500, 270);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        font = new Font("Times New Roman", Font.BOLD, 14);

        panel = new JPanel();
        panel.setLayout(null);
        panel.setOpaque(true);
        fileField = new JTextField();
        fileField.setFont(font);
        fileField.setBounds(130, 110, 200, 25);

        Font font2 = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 12);
        message = new JLabel("Type in the file name with it's extension. eg: File.txt");
        message.setFont(font2);
        message.setBounds(130, 140, 280, 25);
        message.setOpaque(true);

        uploadBtn = new JButton("UPLOAD");
        uploadBtn.setFont(font);
        uploadBtn.setBounds(340, 110, 95, 21);

        panel.add(fileField);
        panel.add(uploadBtn);
        panel.add(message);

        add(panel);

    /////// register event
        uploadBtn.addActionListener(this);
        exit.addActionListener(this);

    }

    public void actionPerformed(ActionEvent ev) {
        String file = fileField.getText();

        SetGetQuestionFileName setGet = new SetGetQuestionFileName(file);

        FileInputStream fis = null;
        PreparedStatement preparedStmt = null;

        try {
            String myUrl = "jdbc:mysql://localhost:3306/testsystem";

            Connection conn = DriverManager.getConnection(myUrl, "root", "cput");

            if (ev.getActionCommand().equals("UPLOAD")) {
                File filePathString = new File(file);

                fis = new FileInputStream(filePathString);

                if (fileField.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "File field can't be empty. Try again", "ERROR", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    if (filePathString.exists() && filePathString.isFile()) {

                        try {
                            // the mysql insert statement
                            String query = " insert into users (category_questions, questions, quest_opt_a, , quest_opt_b, , quest_opt_c,  quest_opt_d, correct_option_answer )"
                                    + " values (?, ?, ?, ?, ?)";

                            // create the mysql insert preparedstatement
                            preparedStmt = conn.prepareStatement(query);
                            preparedStmt.setString(1, "JDBC");
                            preparedStmt.setString(2, fileField.getText());
                            preparedStmt.setAsciiStream(3, fis, (int) filePathString.length());
                            //preparedStmt.setString   (3, "a");
                            preparedStmt.setString(4, "b");
                            preparedStmt.setString(5, "c");
                            preparedStmt.setString(6, "d");
                            preparedStmt.setString(7, "a");

                            preparedStmt.executeUpdate();

                            // execute the preparedstatement
                            preparedStmt.executeUpdate();
                            //  myfile.closing();
                            conn.close();

                            JOptionPane.showMessageDialog(null, "File successfuly uploaded", "INFORMATION", JOptionPane.INFORMATION_MESSAGE);
                            fileField.setText("");
                        } catch (Exception ex) {
                        } finally {
                            preparedStmt.close();
                            fis.close();
                            conn.close();
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "File coudn't be found. Do check file name.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        } catch (Exception ex) {
        }

        if (ev.getActionCommand().equals("LOGOUT")) {
            System.exit(0);
        }
    }
}

SetQuestionFileName class
public class SetGetQuestionFileName {

    String myfile;

    public SetGetQuestionFileName(String file) {
        setFileName(file);
    }

    public void setFileName(String file) {
        myfile = file;
    }

    public String getFileName() {
        return myfile;
    }
}

Comment: please try to "format" your code a little bit and if possible break it down.. e.g you could remove the `import` statements. As it is right now, it is not readable
Comment: i've edited it don't know if it's better now in this way
Comment: where do you read the file? I see a `fis = new FileInputStream(filePathString);` but then you build the prepared Statement without touching `fis` again. Or am I missing something?
Comment: actually i was using this way to read the file but i removed it because it was not working.
    FileReader filePath = new FileReader(details.getFileName()); // read characters at a time
          BufferedReader fileNames = new BufferedReader(filePath); //helps read file lines at a time

          while((line = fileNames.readLine()) != null)
          {

           arrayOutput.add(fileNames.readLine());
          }
         }
Comment: i don't know if i'm doing the correct thing. i have file which contains questions which are in the following way : "Category Questions " then question then the options and then a blank line and then the correct answer
Comment: basically, what i want is to read the file text content for now and insert it into the database.
Answer: Here a short version on how you can read a file (line by line):
Scanner scanner = new Scanner(filename);
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
}

This is your query. There where too many , or empty column names and the number of columns and ? does not match:
String query = " insert into users (
                        category_questions,
                        questions,
                        quest_opt_a,
                        ,              // empty column name
                        quest_opt_b,
                        ,              // empty column name
                        quest_opt_c,
                        quest_opt_d,
                        correct_option_answer
                )" + " values (?, ?, ?, ?, ?)"; // you have 7 columns (without the empty ones) but only 5 ?

Here a reformatted version of your query. I just removed the , and added 2 ?
String query = "INSERT INTO users (
                        category_questions,
                        questions,
                        quest_opt_a,
                        quest_opt_b,
                        quest_opt_c,
                        quest_opt_d,
                        correct_option_answer
                 ) VALUES (?, ?, ?, ?, ?, ?, ?)";

Now I am trying to understand the values you want to add:
preparedStmt.setString(1, "JDBC");    // so JDBC is your category ?
preparedStmt.setString(2, fileField.getText()); // I guess this should be the question?
preparedStmt.setString(3, "a");       // according to the column names this needs to be option A
preparedStmt.setString(4, "b");       // option b
preparedStmt.setString(5, "c");       // option c
preparedStmt.setString(6, "d");       // option d
preparedStmt.setString(7, "a");       // answer

So far so good. If I interpreted the column names correctly, this should work. The only thing left is now to get the real question text for column 2 (from the file).
I don't know how your file looks like, so I can just give you an example:
textfile in this format:  question? answerA, answerB, answerC, answerD, correctAnswer
-------------------------------------------------------------------------------------
What is the color of the sun? pink, blue, yellow, green, c
What is the smallest number? 3, 1, 7, 200, b

And this would be how you could read the file and fill the database all at once:
// prepare the query
String query = "INSERT INTO users (
                        category_questions,
                        questions,
                        quest_opt_a,
                        quest_opt_b,
                        quest_opt_c,
                        quest_opt_d,
                        correct_option_answer
                 ) VALUES (?, ?, ?, ?, ?, ?, ?)";

// load the file
Scanner scanner = new Scanner(filename);
// read the file line by line
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();

    String[] questionAnswer = line.split("?")[ // line.split["?"] will split the line into two strings, right at the ? and put those two strings into an array.
    String question = questionAnswer[0]  // so [0] will access the first element in that array - the question
    String[] answers = questionAnswer[1].split(","); // now we split the string after the ? into many strings divided by comma

    preparedStmt.setString(1, "JDBC");
    preparedStmt.setString(2, question);
    preparedStmt.setString(3, answers[0]);
    preparedStmt.setString(4, answers[1]);
    preparedStmt.setString(5, answers[2]);
    preparedStmt.setString(6, answers[3]);
    preparedStmt.setString(7, answers[4]);

    preparedStmt.executeUpdate();
}

There are many ways to read the line from your text file and split it into question and answer. It depends on the file you read from and how it is formatted.
FIY: you execute preparedStmt.executeUpdate(); twice at the end :)
Comment: sorry, that's exactly how the file looks like   The format would be:
Category   (One of 4.  For example Combinational Logic)
Question   (One or more lines)
Four alternative answers (Labelled a., b., c., d.  One or more lines, each.)
Blank line
The correct option  (a., b., c. or d.  Only one option would be correct)
Two Blank lines
Comment: For example for the bellow question, i shall have in my Category_questions : Collections, and for my questions : Which of these is not an example of a "real-life" collection? and for my quest_opt_a : a. The cards you hold in a card game. etc and for correct_option_answer i shall have d insrted in the database table. this is the question  Collections
Which of these is not an example of a "real-life" collection?
a. The cards you hold in a card game.
b. Your favorite songs stored in your computer.
c. The players on a soccer team.
d. The number of pages in a book.

d.
Comment: from what you explained above, i managed to get this, but now it's not only inserting and my upload button has become unresponsive, it doesn't trigger any event now. please i really need help
Comment: i don't know if you had a look at my last attempts


How can one team "own" another team's first-round pick?

Question: For instance, the byline to this Bleacher Report article reads "The Cleveland Cavaliers own the Brooklyn Nets' first-round pick in the 2018 NBA draft."
How can one team own another team's first-round pick?
Answer: Draft picks are an asset, and (in the NBA anyway) they can be traded between teams (subject to some restrictions). Whichever team has the pick on the day of the draft gets to select a player and have exclusive rights to that player, independent of which team the pick was originally assigned to - but the original assignment still determines where the pick falls in the order; hence the pick of a losing team like Brooklyn is more valuable than that of a winning team like the Warriors.
In this case, Brooklyn traded the pick to the Celtics as part of the Kevin Garnett/Paul Pierce trade, and the Celtics then further traded that pick to the Cavaliers as part of the Kyrie Irving/Isaiah Thomas trade.


Ajuda com Json para pegar valor de API

Question: Estou tentando conseguir apenas o retorno de uma variavel dessa api "buy" que seria o valor de compra, porém quando tento ela me retorna a tabela toda, alguém poderia me iluminar?
$data = json_decode(file_get_contents("https://broker.negociecoins.com.br/api/v3/btcbrl/ticker"));
echo "
";
print_r($data);
echo "
";

Comment: print_r($data->$buy);
Comment: Deu certo, muito obrigado.
Comment: @LucasBrogni corrigindo, o correto é $data->buy
Answer: Utilize  print_r($data->buy);
Comment: Bom dia, não deu certo Lucas, continou sem me retornar nada. se eu tiro o Buy, ele retorna tudo, com o buy, ele me retorna nada, meu código ficou assim.

";
  print_r($data->buy);
  echo ""; ?>
Comment: @EduardoCardosodossantos ali no comentário da pergunta, você tinha dito que tinha funcionado '-'
Comment: funcionou com aquele api da questão, porém testando com outros não funcionou, como esse do exemplo acima, não entendi o motivo, a sintax é a mesma.
Comment: @EduardoCardosodossantos acessei a API agora. Ele não funciona nesta outra por que o retorno dela não é diretamente o buy:

`{
message: null,
data: {
high: 27200,
low: 25000,
volume: 182.71434794,
trades_quantity: 2538,
last: 25317.7,
sell: 25269.32,
buy: 25253,
date: "2018-08-08T11:36:18.909Z",
},
}`
Existe um data dentro dele. Adicione ->     Nesse caso use `print_r($data -> data -> buy)`

Ajuda com Json para pegar valor de API


Distance of the stave lines?

Question: I have not found definite answers for these two doubts, can anyone help me?

At what distance should the stave lines be?
What distance should be between staves?
Comment: You won't find a definitive answer because it depends. I would research the intended ensemble or musicians and see what they want. For example, major concert orchestras are likely to prefer the MOLA guidelines, orchestras for scoring film and TV will have very different standards, bands will use another set of standards, chamber ensembles will have their own preferences, etc.
Comment: Related: [Standard staff size](https://music.stackexchange.com/questions/61870/standard-staff-size?)
Comment: What size paper are you using?  Is it a part or a score?  If a part, it it for a singer or an instrumentalist?  If it is a score, how many staves are in each system?  The answer depends on all of these factors and probably more.
Answer: The distances depend on the type of score being produced.
The standard reference for all things notation related is Behind Bars by Elaine Gould (Faber, 2011). Page 483 includes a table of staff sizes according to purpose. For example

Full score, staff height = 3.7mm
Single-stave parts, piano music, songs = 6.5mm or 7mm.

For the distance between staves, Gould indicates that

Staves should be at least a stave height apart. (p. 488, "Distance between Staves")

and

When a page contains more than one system, the distance between systems should, if possible, be greater than the distance between the most widely spaced staves on an adjacent system. (p. 488, "Distance between Staves")

The book is quite detailed and extensive in describing staff size and distance according to musical context (e.g., instrument types, number of instruments, alignment across pages, etc.), so it's recommended to obtain a copy to find the details specific to the situation at hand. Most libraries containing a music section should have a copy.
Comment: Hm, I wouldn't hold it that strictly. Back in the day of traditional pewter plate engraving the rastral height would have been determined by the sets of stencils used. As each publisher had their own stencils and there is no actual industry norm for engraving stencils there are lots of variations, so I would take these as a general reference rather than a strict rule.
Comment: @user94924 it depends on what kind of notebook it is and on who printed it.
Comment: If I bought a Blank Sheet Music Notebook, for writing music, what would the above distances be?
Comment: You might suggest looking more precisely at the intended audience for the printed music. For example, the [MOLA guidelines](https://mola-inc.s3.eu-west-1.amazonaws.com/files/mola3/MOLA-Guidelines-for-Music-Preparation.pdf) say "The minimum legible staff size for scores is 4 mm", so they want slightly bigger staves than Gould recommends, and anyone producing scores for a major orchestra would be wise to consider MOLA's guidelines over Gould's.
Comment: Although Gould's book is a very good reference (bought one a while ago!) I've used, and still use, different sizes sometimes even enlarging certain music for ease of reading. So, I don't believe there is an 'industry standard' for this, world wide.
Comment: Gould recommends >6.5mm for parts, but in practice anything less than 7mm is hard to read for anybody over 30.
Answer: Staff height and the distance between them  is always a compromise between legibilty and putting as much music as possible on the page.
The minimum staff height is going to depend on the purpose of the music and how far away the player is going to be from the music.
MOLA (The Major Orchestra Librarian's Assocation) Guidelines for Music Preparation recommend staff hights:

full scores: at least 4mm
wind parts at least 7mm
other parts 7.5mm to 8.5mm

Educational music for children can be larger.
The distance between staves will depend on how much the music extends vertically on each one. If there are a of of very high notes and low notes, possibly with articulations and other markings then to  a lot more space between staves is needed, so the the low notes from one system don't get in the way of the high notes from the one below. The space between staves is going to influence how many systems fit on a page. For most types of part ten staves on a page (A4) is a good average. For very simple music twelve might fit. For very complicated music probably less than ten.
For pages with only a few systems, most notation programs offer an option to space the staves equally over the page. Don't do this, it makes the music harder to read,
Comment: @phoog Orchestral wind players play one to a part, strings two to a part so they're farther away. Percussion players mostly need to be farther from the music because they have instruments in the way.
Comment: Why smaller for winds?  It seems that they're recommending the same larger size for both brass and strings.  I can see why a trombonist might need to be farther from the stand than an oboist, because of the slide, and strings, obviously, because they share, but trumpets?  Horns?  It's intriguing.  Do you know why?
Answer: For what it's worth, the default staff height in LilyPond is 20 points, which is about 7 mm†. The font that generates the glyphs comes in versions intended for staves of the range of 3.9 mm – 8.9 mm
The vertical distances between staves and systems are flexible based on context, and of course everything in LilyPond is adjustable.
I checked a couple blank staff notebooks I had on hand and found:
Carl Fischer AC112, 12 staves per page: about 8 mm height, 12 mm spacing.
Mel Bay MB93694, 12 staves per page: about 9 mm height, 13.5 mm spacing (larger pages than the Carl Fischer).
The back cover of the Mel Bay notebook lists other manuscript products. There are student books with as few as 5 staves per page.  This suggests a much larger spacing (just as you would expect on lined writing paper intended for children), but the page size isn't listed so it's impossible to guess exactly the staff height or spacing.

†LilyPond uses American points, AKA TeX points(1/72.27 inch), not Desktop publishing points, AKA PostScript points of 1/72 in.)

Distance of the stave lines?


How reduce in javascript work if initial value is array

Question:

var a = [2,4,5,6,7]
a.reduce((acc,cur,i)=>acc,[])
//result : []
a.reduce((acc,cur,i)=>acc,[0,2])
//result (2) [0, 2]
a.reduce((acc,cur,i)=>acc[0],[0,2])
/*
VM410:1 Uncaught TypeError: Cannot read property '0' of undefined
    at <anonymous>:1:26
    at Array.reduce (<anonymous>)
    at <anonymous>:1:3
    */

why am I getting error for the third one?
Wondering how it works?
Comment: First iteration `acc = [0, 2]` you return `0` (the number). Second iteration `acc = 0`
Comment: your return value on each iteration becomes `acc` for next iteration, so when you do `acc[0] which is 0` so on next iteration you're doing `0[0]` which returns undefined and then `undefined[0]` is syntax error
Comment: @CodeManiac no `0[0]` is fine - it produces `undefined`. Next iteration there us a TypeError because of `undefined[0]`
Comment: @VLAZ ahh thanks for pointing fixed my comment
Answer: Your code does not return an array. However, the accumulator will be set to that value. So while you assume that acc is an array, it is not after the first call to the accumulation function.
What you can do instead is something along the following lines:

    var a = [2,4,5,6,7];
    a.reduce((acc,cur,i) => {
            acc.push(cur);
            console.log(`iter ${i}, acc = ${JSON.stringify(acc)}.`);
            return acc;
       }
      ,[0,2]
    );

Just make sure that your callback returns an array upon each invocation.
Answer: The reduce function works as a for loop, where a variable (acc) gets set at every iteration:
The first two examples you gave:
var a = [2,4,5,6,7]

a.reduce((acc,cur,i) => acc, [])
a.reduce((acc,cur,i) => acc, [0, 2])

Are equivalent to assigning the accumulator to itself at each iteration:
var acc = []; // [0, 2] in the second one

for(var i=0; i < a.length; i++){
    acc = acc;
}

Whereas your last example:
a.reduce((acc,cur,i) => acc[0], [0, 2])

Is equivalent to assigning to acc its first value at each iteration:
var acc = [0, 2];

for(var i = 0; i < a.length; i++){
    acc = acc[0];
}

Each iteration will assign to acc its first value.
The first iteration will look like this:
acc = [0, 2];
i = 0

acc = acc[0] // 0;

The second iteration will then look like this:
acc = 0;
i = 1

acc = acc[0] // undefined;

Now acc has been assigned the value undefined as there is no such property 0 in the value held by acc.
The third iteration will, therefore, look like this:
acc = undefined;
i = 2;

acc = acc[0]; // Error, no property '0' of undefined.

Answer: An excerpt from mdn documentation for Array.reduce

initialValue -A value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first
  element in the array will be used as the initial accumulator value and
  skipped as currentValue. Calling reduce() on an empty array without an
  initialValue will throw a TypeError.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce


Problemas para utilizar o switch no JS

Question: Oi pessoal estou com um problema que não sei resolver.
Eu este eu quero trocar o numero de um mês pelo nome do mês tipo assim :
( 2/2013 para Fevereiro/2013 ).
No código abaixo eu estou fazendo que ele faça eu lista na ordem cronológica por mes/ano.
E queria saber como faço para trocar agora o numero do mês pelo nome do que corresponde a ele.
=======HTML=====

Tarefa colocar em ordem cronológica ( Mes/Ano)

12/2014
1/2015
11/2014
2/2013

=======JS======
$(document).ready(function(){
    var $sort = $('a');
    var $list = $('.galeria');
    var $listLi = $('a',$list);
    $listLi.sort(function(a, b){
        var keyA = $(a).attr('data-order');
        var keyB = $(b).attr('data-order');
        return (keyA > keyB) ? 1 : 0;
    });
    $.each($listLi, function(index, row){
        $list.append(row);
    });

function trocarNomeMes(mes) {
    switch ( mes ) {
        case 1: mes = "Janeiro";
        break;

        case 2: mes = "Fevereiro";
        break;

        case 3: mes = "Março";
        break;

        case 4: mes = "Abril";
        break;

        case 5: mes = "Maio";
        break;

        case 6: mes = "Junho";
        break;

        case 7: mes = "Julho";
        break;

        case 8: mes = "Agosto";
        break;

        case 9: mes = "Setembro";
        break;

        case 10: mes = "Outubro";
        break;

        case 11: mes = "Novembro";
        break;

        case 12: mes = "Dezembro";
        break;
    }
    return mes;
}

});

LINK JSFIDDLE:
https://jsfiddle.net/websmallville/2yk8mwh3/1/
Onde estou errando..?!?
Answer: Você pode separar a data em 2 pedaços, e remontar o conteudo assim

$(document).ready(function(){
    var $sort = $('a');
    var $list = $('.galeria');
    var $listLi = $('a',$list);
    $listLi.sort(function(a, b){
        var keyA = $(a).attr('data-order');
        var keyB = $(b).attr('data-order');
        return (keyA > keyB) ? 1 : 0;
    });
    $.each($listLi, function(index, row){
        var dataslice  = $(row).text().split("/");
        $(row).text(trocarNomeMes(dataslice[0])+"/"+dataslice[1]);
        $list.append(row);
    });

    function trocarNomeMes(mes) {
        switch ( mes ) {
            case "1": mes = "Janeiro";
            break;

            case "2": mes = "Fevereiro";
            break;

            case "3": mes = "Março";
            break;

            case "4": mes = "Abril";
            break;

            case "5": mes = "Maio";
            break;

            case "6": mes = "Junho";
            break;

            case "7": mes = "Julho";
            break;

            case "8": mes = "Agosto";
            break;

            case "9": mes = "Setembro";
            break;

            case "10": mes = "Outubro";
            break;

            case "11": mes = "Novembro";
            break;

            case "12": mes = "Dezembro";
            break;
        }
        return mes;
    }

});

.galeria a {
    margin-right: 5px;
    padding: 4px;
    border-radius: 2px;
    font-size: 14px
    list-style: none;
    text-decoration: none;
    display: block;
    float: left;
    color: #fff;
    background-color: #F07C6C;
}
.galeria a:hover {
    background-color: #62707A;
}

Tarefa colocar em ordem cronológica ( Mes/Ano)

12/2014
1/2015
11/2014
2/2013

jsfiddle
No switch você está usando uma variável para armazenar o valor para depois retornar, você poderia fazer isso diretamente.
switch ( mes ) {
            case "1": return "Janeiro";
            break;

            case "2": return "Fevereiro";
            break;

            case "3":return"Março";
            break;

            case "4": return "Abril";
            break;

            case "5": return "Maio";
            break;

            case "6":return "Junho";
            break;

            case "7": return "Julho";
            break;

            case "8": return "Agosto";
            break;

            case "9": return "Setembro";
            break;

            case "10": return  "Outubro";
            break;

            case "11":return ovembro";
            break;

            case "12": return  "Dezembro";
            break;
        }

Comment: Obrigado Isvaldo pela ajuda e explicação. :D

Problemas para utilizar o switch no JS


Picture field in user table

Question: I can see the picture field in the user table, and it seems the field accepts a picture address.
I want to allow users to upload their picture to the site.
Is there any module or code to use this field?
Answer: Check the user account settings in page admin/user/settings, the option for changing user picture is "Picture support."
Comment: thank u.can we use imagecache for uploaded user picture?
Answer: User pictures, the pictures associated with a user account, are handled from the User module.
You need to enable their support with the "Picture support" option you find in admin/user/settings.
The support works if the directory for the files has been correctly set, and Drupal has the permission to write files in that directory; the path reported in "Picture image path" must exists.
Comment: thank u.can we use imagecache for uploaded user picture?
Comment: @a.v You can use Imagecache with any images uploaded to Drupal, including the ones uploaded with the Upload module.
Comment: i can use imagecache with cck  field but how to set imagecache for upload user picture field (upload module?). more help plz.
Comment: Imagecache creates only copies with different dimensions of an image that has been uploaded to a Drupal site; it doesn't upload the image itself, and you can use any module for uploading the image.

Picture field in user table


Ajax upload não envia imagem e nem parametro

Question: Estou tentando fazer um upload sem From, para upload de imagem, mas não consigo.
html
<input id="avatar" type="file" name="avatar" />
<button id="btnOcorrenciaSalvar">Salvar</button>

Código javascript:
$("#btnOcorrenciaSalvar").click(function() {

                event.preventDefault();
                var form_data = new FormData();
                nomeFoto = event.filename;

                var file_data = $("#avatar").prop("files")[0];

                form_data.append("file", file_data)
                form_data.append("foto", nomeFoto)

                $.ajax({
                  url: 'http://url.com.br/temp.php',
                  type: 'POST',
                  data: form_data,
                  async: false,
                  cache: false,
                  contentType: false,
                  processData: false,
                  success: function (returndata) {
                      //$("#productFormOutput").html(returndata);
                      alert(form_data);
                  },
                  error: function () {
                      alert("error in ajax form submission");
                  }
                });

                return false;

            });

Código PHP para receber o POST:
<?php
    move_uploaded_file($_FILES["avatar"]["tmp_name"], "ocorrencias/" . $_POST["foto"]);
?>

Answer: Se você utilizasse um form seria bem mais simples:
<form id="formulario" method="post" enctype="multipart/form-data" action="upload.php">
  <input type="file" id="imagem" name="imagem" />

</form>

js
$(document).ready(function () {
    /* #imagem é o id do input, ao alterar o conteudo do input execurará a função baixo */
    $('#imagem').live('change', function () {
        $('#visualizar').html(' Enviando...'); /* Efetua o Upload sem dar refresh na pagina */
        $('#formulario').ajaxForm({target: '#visualizar' /* o callback será no elemento com o id #visualizar */}).submit();
    });
});

Comment: Bom dia. Esta aparecendo esse erro ``Uncaught TypeError: undefined is not a function ``. na linha onde tem o ``$('#formulario').ajaxForm``. O que é isso?
Comment: no lugar do #formulario deve ficar o id do seu formulário!
Answer: O erro Uncaught TypeError: undefined is not a function, é porque foi utilizado o plugin ajaxForm, e você não importou ele.
Se quiser continuar usando jQuery sem plugins, coloque um:

var_dump($_FILES);

Para entender o que está realmente sendo enviado pelo teu javascript.
Answer: Acredito que é porque você esqueceu de declarar o parâmetro event da função click(), ex:
$("#btnOcorrenciaSalvar").click(function(event) {
e você chamou sem ele existir: event.preventDefault();


Why is $\lfloor n/3 \rfloor + \lceil 2n/3\rceil = n?$

Question: Why is $\lfloor n/3 \rfloor + \lceil 2n/3\rceil = n?$
It feels like I'm just doing basic fraction addition since
$$\frac{n}{3}+\frac{2n}{3}=n$$
So then how does ceil and floor play a role in addition?
Comment: $n/3$ and $2n/3$ are not always integral. So, for example, $n/3$ does not always equal $\lfloor n/3 \rfloor$. A natural way of approaching such a problem is to realize that any integer $n$ can be written as either $3k$, $3k+1$ or $3k+2$, with $k \in \mathbb{Z}$. Now we can check these $3$ cases separately.
Comment: If you check the plot http://www.wolframalpha.com/input/?i=floor(x%2F3)%2Bceil(2x%2F3),+x you'll notice that the equality only holds for integer $n$. The pure fractional equation holds for all numbers.
Answer: Let $n=3k + r$, where $r\in \{0,1,2\}$. Then $\lfloor\frac{n}{3}\rfloor = k$. Also, $\lceil\frac{2n}{3}\rceil=\lceil\frac{6k + 2r}{3}\rceil=2k+\lceil \frac{2r}{3}\rceil$. Therefore, $$\left\lfloor\frac{n}{3}\right\rfloor + \left\lceil\frac{2n}{3}\right\rceil = 3k + \left\lceil\frac{2r}{3}\right\rceil.$$ The claim immediately follows by noting that $\lceil\frac{2r}{3}\rceil = r$ for $r \in \{0,1,2\}$.
Answer: Note that both $\frac n3-\left\lfloor\frac n3\right\rfloor$ and $\left\lceil\frac{2n}3\right\rceil-\frac{2n}3$ have a period of $3$. Subtracting we get that
$$
\left\lceil\frac{2n}3\right\rceil+\left\lfloor\frac n3\right\rfloor-n\tag{1}
$$
has a period of $3$. Thus, we only need to check $n=0,1,2$ to verify
$$
\left\lceil\frac{2n}3\right\rceil+\left\lfloor\frac n3\right\rfloor=n\tag{2}
$$
for all $n$.
Answer: Note that the following identities hold for all integer $n$, real $x$:

$\lceil n+x \rceil = n + \lceil x \rceil$ (and $\lfloor n+x \rfloor = n + \lfloor x \rfloor$, but we don't need that)
$\lceil -x \rceil = -\lfloor x \rfloor$

Thus, if $n$ is an integer, we have:
$$\lceil 2n/3 \rceil=\lceil n+(-n/3)\rceil=n+\lceil -n/3\rceil=n-\lfloor n/3\rfloor$$
Answer: Hint: do the actual computation (with floor and ceiling) for various sample values of $n$ - say $1$ through $6$.
You'd better assume $n$ is an integer. Can you see why?
Comment: One can even spare one sample, $n=6$ is not needed.
Answer: For ease of typing let $f(z)=floor(z)$ and $c(z)=ceil(z).$
We have  $n=3m+x$ where $m\in \mathbb Z$ and $x\in \{0,1,2\}.$
(i). If $x=0$ then $f(n/3)+c(2n/3)=f(m)+c(2m)=m+2m=3m=3m+x=n.$
(ii). If $x=1$ then $f(n/3)+f(2n/3)=f(m+1/3)+f(2m+1/3)=m+(2m+1)=3m+1=3m+x=n.$
(iii). If $x=2$ then $$f(n/3)+c(2x/3)=f(m+2/3)+c(2m+4/3=f(m+2/3)+c((2m+1)+1/3)=$$ $$=m+(2m+2)=3m+2=3m+x=n.$$


Use of resolv.h

Question: I'm trying to find out my DNS server address by reading it from resolv.h's _res struct. According to man 3 resolver the setup code should be.
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>

extern struct state _res;

and then I just read out whatever I need. My problem is that trying to compile this I get
resolver.c:5:21: error: conflicting types for '__res_state'
extern struct state _res;
                    ^
/usr/include/resolv.h:251:16: note: expanded from macro '_res'
#define _res (*__res_state())
               ^
/usr/include/resolv.h:249:28: note: previous declaration is here
extern struct __res_state *__res_state(void) __attribute__ ((__const__));
                           ^
1 error generated.

by clang.
What am I doing wrong?
Answer: You shouldn't declare _res yourself - resolv.h includes the right declaration (despite what the man page implies).
Answer: #include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>

int main() {

    // call this first
    res_init();

    // do something with this list it contains list of dns servers
    _res.nsaddr_list[0];

}

Use of resolv.h


Qual utilidade real do SqliteOpenHelper no Android?

Question: Estava vendo um curso da devmedia online explicando sobre Sqlite no Android, no exemplo do curso foi feito um crud básico, foram criadas 1 banco e 2 tabelas.
No exemplo, estava criando duas classes que estendiam a SqliteOpenHelper, e cada classe manipulava uma tabela, ou seja, o exemplo estava usando o SqliteOpenHelper para gerenciar o banco e dados das tabelas!!
Depois de pesquisar por fora, vi que quando se cria o banco, o sqlite gera o cache dele, o que poderia gerar um grande problema neste caso do exemplo. E vi um exemplo de um site que foi usado uma classe separada para manipular as tabelas!

Então estou confuso, o SqliteOpenHelper serve somente para criar o banco?
Não se deve manipular dados das tabelas por ele (criando várias classes do SqliteOpenHelper, para cada tabela)?
Se ele serve somente para gerenciar o banco (sem as tabelas), eu teria que criar todas tabelas na mesma classe do SqliteOpenHelper? Neste caso, se um usuário remover alguma tabela, como ela retornaria?

Não tenho como enviar o link do devmedia, pois o acesso é somente para assinantes.

Exemplo gerenciando tabelas fora do helper:
  http://pplware.sapo.pt/smartphones-tablets/android/tutorial-utilizao-do-sqlite-no-android-parte-i/
Comment: Não conheco o uso de SQLite no Android mas conheço o histórico de cursos e artigos da DevMedia. Muitos são legais, ajudam mesmo. Mas já vi cada besteira também. E os leigos (a maioria de quem lê, óbvio) acham que é bom o que não é. Nada contra a dizer sobre este curso, apenas um alerta geral. Bom, na verdade qualquer um pode escrever besteira, eu posso fazer isto, então o alerta é mais amplo.
Comment: eu estive percebendo isso depois de notar várias bobeiras, que só fui perceber depois de pesquisar a fundo no Google. Pelo menos a minha pergunta serve de aviso, para prestarem atenção antes de assinarem algo.
Comment: Estive pesquisando, e parece que realmente a função do SqliteOpenHelper. é de apenas facilitar a criação do banco pelos métodos onCreate e onUpdate. Mas ainda assim estou em dúvida sobre as criações de tabelas, se todas devem ser criadas no SqliteOpenHelper, e manipuladas em outra classe
Comment: Eu acho que a ideia principal do `SQLiteOpenHelper` é a configuração inicial da aplicação (seja na primeira instalação, onde as tabelas ainda não foram criadas) quanto para evolução (upgrade e downgrade de versão de banco). Não se deve usar ele diretamente para consultas. Na documentação está claro isso ("A helper class to manage database creation and version management"). Acredito que para consultas em banco não se deve usar ele, o melhor a se fazer é usar `ContentProvider's`, `Cursor's` ou no máximo um `SQLiteDatabase` para consultas rápidas, se for algo assíncrono use um `CursorLoader`.
Comment: @Wakim se puder responder, para eu aceitar... Acho que não vai aparecer nenhuma resposta
Answer: Eu acho que a ideia principal do SQLiteOpenHelper é a configuração inicial da aplicação (seja na primeira instalação, onde as tabelas ainda não foram criadas) quanto para evolução (upgrade e downgrade de versão de banco).
Na documentação está claro isso:

A helper class to manage database creation and version management.

Não se deve usar ele diretamente para consultas, porque existem formas melhores para ser fazer isso.
O melhor a se fazer é usar ContentProvider's/ContentResolver's, Cursor's ou no máximo um SQLiteDatabase para consultas rápidas. Se a ideia é fazer consultas assíncronas, use um CursorLoader.
No pior dos casos, até um ORM é válido. Exemplos: OrmLite, greenDAO, Sugar ORM e o Active Android.
Opinião pessoal:
Eu costumo usar CursorLoader, ContentProvider's e Cursor. Tenho um app que usa o Active Android, mas se eu tivesse tempo de refazer, usaria de fato CursorLoader mesmo.
Não irei colocar exemplos de códigos porque senão fugirá muito do escopo da pergunta.


core.gitProxy and GIT_PROXY_COMMAND appear to do nothing

Question: I tried to set up a proxy for git (git protocol, not https), using these instructions. Git appeared to work whether or not the proxy was actually running, which led me to believe it wasn't actually using the proxy at all, and was silently "failing open".
I experimented with the config to try and find out what was going on, as you can see below.
$ git config --global core.gitProxy 'touch /tmp/test'
$ unset GIT_PROXY_COMMAND
$ git ls-remote email@example.com:redacted/redacted.git
...
$ file /tmp/test
/tmp/test: ERROR: cannot open `/tmp/test' (No such file or directory)
$ git --version
git version 220.127.116.11

How can I get the proxy to work, and be sure that it is working? How can I get it to "fail closed"?
Answer: As usual, the problem lies with assumptions in my own question. It turns out that the firstname.lastname@example.com:redacted/redacted syntax does not use the git protocol, it uses the ssh protocol. So I need to configure the proxy as part of ssh, not git. One (ugly) way of doing that is like so:
$ echo 'ProxyCommand touch /tmp/test' > ~/.ssh/config
$ git ls-remote firstname.lastname@example.com:redacted/redacted.git
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
$ file /tmp/test
/tmp/test: empty

Answer: you can use GIT_SSH env variable point to a script wrapper with content ssh -o ProxyCommand='touch /tmp/test' $@


Bootstrap - how to add row number automatically?

Question: how to add row number automatically?
I donot want to use json data, does bootstrap have this ability to add rom numbers?
Comment: row numbers ... in what?
Comment: @zakiye M, please provide detail about your doubt. Cant understand which row you taking about.
Answer: If you use ordered element in bootstrap it will number will come automatically

...

Answer: No, bootstrap itself does not do what you are asking.  If you are using another framework with it, the framework may provide you need you need.  (eg. angular uses $index for the loop index), or you can use some jquery to reference elements in your array.   Unless I am misunderstanding your question, bootstrap itself will not provide what you need.