Sum of the reciprocals of the products of primes

Question: Q. Find an upper bound for the following sum of an infinite series:
$$\sum(\frac{1}{2\times3}+\frac{1}{5\times7}+\frac{1}{11\times13}+...)$$
The denominator is a series of prime numbers.
I am aware that the sum of an infinite series of reciprocals of primes diverges, but I am told that the summation above converges.
Comment: Well, $\sum_{n=2}^{\infty}\frac 1{n(n+1)}=\frac 12$ gives a start.
Comment: Are you looking for an upper bound or for a way to compute the series?    It's easy to improve my bound in small ways (delete unhelpful terms like $\frac 1{3\times 4}$ and so on).  Or use it to compute the series by adding the first hundred terms of yours, then using my bound to cap the error.
Comment: I wrote a small program, and the sum seems to converge to somewhere below 0.3. Can the upper bound be tighter than that?
Comment: It would be best if the summation can be computed.
Comment: I just gave an (easy) way to compute the series numerically.  I don't see an analytic way to compute it (which does not mean that there isn't one).
Answer: A similar sum, which also includes the other half of the products like 1/(3*5), 1/(7*11) and so on, is discussed in https://oeis.org/A210473 and I have posted estimates of that sort in a PDF file in a URL in https://oeis.org/A209329 .
Answer: Here is another hint.  Your sum of "adjacent" prime reciprocals is obviously less than:$$\frac1 {2^2}+\frac 1 {4^2}+\frac 1 {6^2}+...=\frac 1 4.\frac {\pi^2} 6=\frac {\pi^2} {24}=0.411 (approx.)$$  With only a bit more cunning I am sure that this upper bound could be improved significantly.
Here is another much better method:  Your sum is less than the following sum:$$\frac 1 {2.3}+\frac1 {5.7}+\frac1 {11.13}+\frac1 {17.19}+\frac1 {23.25}+...+\frac1 {(6n-1)(6n+1)}+...$$  This is easily shown to be (by treating the first term alone and then the rest as a simple infinite series using the cotangent expansion): $$\frac1 6+\frac1 {12}(6-\sqrt3\pi)=0.213216826...$$  This gives a much tighter upper bound for the prime series of fractions (the first four terms are the same!).  By actual numerical calculation, the original infinite sum involving prime numbers is just a little over 0.21, slightly less than this upper bound just calculated.


R - Change the order of characters in a list

Question: Hello i have this list
<code>    LIST<-list(list("DC,MD,MA,Washigton,Baltimore,Boston,France,Turkey,China"),
           list("DC,MD,Washington,Baltimore,France,Turkey"),
           list("DC,Washington,France,Turkey,China")
</code>
I want to change the order of the strings of the sublists according to this logic:
<code>    LIST<-list(list("DC,Washington,MD,Baltimore,MA,Boston,France,Turkey,China"),
               list("x1,y1,x2,y2,z1,z2,z3"),
               list("x1,y1,z1,z2,z3"))
</code>
Note that  x and y have the same count and can be up to 3. Z do not have count restriction. I do not want of course the change the order manually for each sublist but with an automated way.
Answer: <code>library(magrittr)
fun=function(string){
 lapply(strsplit(string,","),function(x)sub("([a-z])([0-9])","\\2\\1",x)%>%
    sort()%>%sub("([0-9])([a-z])","\\2\\1",.)%>%paste(collapse=","))
}

rapply(LIST,fun,how="list")
</code>
After edition:
<code> fun=function(string,NO){
  lapply(strsplit(string,","),function(x)
    paste(c(by(x, c(s<-rep(1:NO,2),rep(0,length(x)-length(s)))
               ,paste0,collapse=",")),collapse=", "))
}
rapply(LIST,fun,how="list",NO=3)
</code>
Comment: Actually this one is more accurate: LIST<-list(list("DC,MD,MA,Baltimore,Washington,Boston,France,China"),
       list("DC,MD,MA,Baltimore,Washington,Boston,France,China,Turkey")) x represents states, y cities and z irrelevant countries. z do not need to match with the others
Comment: What do you need from it? How do you want it arranged?
Comment: State should be near to its city
Comment: Am sorry I don't know the states and cities of America.. You must provide an objective way for one to translate that into a code. How many states How many cities?
Comment: The relation between them is like my initial post: if x1,x2,x3 are the states then the correspondent cities are y1,y2,y3. There can be from 1 to 3 x and y and there are always as many x as y
Comment: Should I add another answer here or would you mind asking another question then I post the answer? This answer I gave specifically answers the question ask. If you don't mind, you might ask that other question and I will post the answer
Comment: i editted the question so you can post here the answer
Comment: except if you want me to accept this answer and begin a new topic.
Comment: I have added both. Well that would be great but as you can see, both solutions have been added
Comment: tnx can you explain me this line?paste(c(by(x, c(rep(1:3,2),rep(3,length(x)-6))
Comment: The `c(rep(1:3,2),rep(4,length(x)-6)` simply creates a vector 1,2,3,1,2,3,4,4 if x is of length 8 or 1,2,3,1,2,3,4,4,4,4,4,4,4,4,4 if the length is 15. I only need the first 6. The rest are grouped together. In those first six, collect the ones together, the twos together, etc etc... then paste them together
Comment: I see..clever! but for some reason it cannot be applied here [[1]]
[1] "MA, WA, Boston, Seattle, France"
Comment: I wrote that in a specific code. Let me edit it for generality ie change the 3 into 2 and also the 2 into 1 I will edit the code for you
Comment: Just NO means number of cities. So if you have 3 you will input 3 etc etc
Comment: I hope it now works. There was a six hat i had left in the code
Comment: it is working `fun("MA, WA, Boston, Seattle, France",2)
[[1]]
[1] " France , MA, Boston ,  WA, Seattle"`
Comment: Hi Onyambu, suppose that it is fun("MA", "WA", "Boston", "Seattle", "France",2) which means that the sublists include separated characters not one character. How could it work? Thanks in advance.
Comment: How can I display city before state?


Adjusted mortality rates

Question: I have some data similar to this
died  age  hospital
0     75     AA
0     88     AA
1     81     AA
0     77     AA
1     65     AA
0     41     AA
0     66     BA
1     81     BA
0     82     BA
1     64     BA
0     65     BA
1     52     BA

I was asked to calculate "age adjusted mortality rates" for each hospital. There are around 150 hospitals and approx 1000 patients (observations) per hospital. Each row in the data concerns a particular patient.
I was told how this could be done in Stata:

Perform logistic regression of died on age.
Use the predict function to get patient-level probabilities of death.
Summarise the patient-level probabilities by hospital to get the mortality rates for each hospital.

However, I am using R.
Is this the correct approach ? Are the alternatives ? Can I do the same thing in R with glm and predict ?
Edit:
I should perhaps add that there are several other variables that are going to be adjusted for in the model. I have shown age above, just for simplicity.
Answer: Seems right. Here are the codes for replication.
died     <- c(0,0,1,0,1,0,0,1,0,1,0,1)
age      <- c(75,88,81,77,65,41,66,81,82,64,65,52)
hospital <- c(rep("AA",6),rep("BA",6))
mydata   <- data.frame(died, age, hospital)
m01 <- glm(died~age, family=binomial)

Now, for prediction:
> predict(m01)
           1            2            3            4            5            6
-0.398530343 -0.547998721 -0.467515748 -0.421525478 -0.283554668 -0.007613048
           7            8            9           10           11           12
-0.295052236 -0.467515748 -0.479013316 -0.272057101 -0.283554668 -0.134086291

which gives predicted ln(odds). And
> predict(m01, type="response")
        1         2         3         4         5         6         7         8
0.4016655 0.3663288 0.3852044 0.3961518 0.4295825 0.4980967 0.4267674 0.3852044
        9        10        11        12
0.3824851 0.4324021 0.4295825 0.4665286

gives predicted probability.
Stata says the same thing (see instruction I used and image I got)
But the more important comment is that in epidemiology, "age-adjustment" can also mean rates that are standardized by a certain reference population make up. You said "you were asked" and "you were told to do that in Stata." If these are told by the same person then I think you're fine. If they are two different people you should go back and clarify if (s)he meant epidemiological adjustment or statistical adjustment.
Also, analytically... I feel that if hospital care is a main factor, then we shouldn't go into the picture assume that the mortality risk is even across hospitals. I think it may make more sense to do the prediction by hospital, and then apply an imaginary patient body across each of the hospitals, and the come up with their relative death rates. This approach seems more "age-adjusted." Alternatively, your other predictors should better include hospital characteristic or even the hospital variable itself.
Comment: Thank you (+1) ! This is helpful. Actually this is not age-adjustment in the sense of a reference population - simply an adjustment via a regression model. But thanks again for mentioning this (actually, after I posted the question I realised this might be inferred and that's why I made the "edit" as there are about 7 other variables that I need to add).
Comment: @P Sellaz Oh, I see. And please also read my last paragraph that I just added. I am not sure about your research question but I felt that can be a potential problem.
Comment: Thanks again. Hospital care /is/ a main factor. Actually the research project was looking at how hospital-level variation in outcomes has evolved over time. I was asked to produce (a summary of) these mortality rates to be used in the abstract for conference presentation, to give some context to the project.
Answer: Well, I've worked it out for myself, though I'm still a little unsure if it is the correct approach.
fit1 <- glm(died~age,family=binomial(link=logit),data=dt)
pr <- predict(fit1, type="response")
dt <- cbind(dt,pr)

hosp.mortality.rates <- by(dt$pr, dt$hospital, mean)

Adjusted mortality rates


Infinitely Often vs Almost Always

Question: Let $A_n$ be an event ($n \in \mathbb{N}$). Why is it that $x$ occuring for all but finitely many $n$ be a subset of $x$ occuring for infinitely many $n$? What if $x \in A_{2k}$, then $x$ will  be occuring for infinitely many $n$, but not be occuring for all but finitely many $n$?
Comment: Yes, it is, in the infinitely many $A_{n}$ for $n=2,4,6,\ldots$.
Comment: It *is* in infinitely many $A_n$: Namely, $$x \in A_2, x \in A_4, x \in A_6, x \in A_8, \dots$$
Comment: $x$ is in infinitely many $A_n$'s.  (More precisely, it's in $A_n$ for infinitely many $n$'s.)  What makes you think it isn't?
Comment: I updated my question, I didn't really ask what I wanted at first!
Answer: "For all but finitely many $n, x\in E_n$" means that the subset of $\Bbb N$ for which $x\notin E_n$ is true is finite. "For infinitely many $n, x\in E_n$" means the subset of $\Bbb N$ for which $x\in E_n$ is true is infinite, i.e, not finite. Note this is different from the previous assertion, as you just have been shown, but the previous assertion implies the last.
ADD The above definition comes up when defining limit superiors and inferior of sets, namely $$E^\ast=\limsup E_n=\{x:x\in E_n\text{ for infinitely many } n\}$$ $$E_\ast=\liminf E_n=\{x:x\in E_n\text{ for all but finitely many } n\}$$
The above discussion implies that $E_\ast\subseteq E^\ast$. One can show, on the other hand, that $$E^\ast =\bigcap_{n\geqslant 1}\bigcup_{k\geqslant n}E_k$$ $$E_\ast =\bigcup_{n\geqslant 1}\bigcap_{k\geqslant n}E_k$$
The above shouldn't be too surprising: if $x$ is in $E_n$ for all but finitely many, we can choose large enough $M$ so that $\{M,M+1,\ldots\}$ doesn't contain said finite set, so $x$ will be in $E_M,E_{M+1},\ldots$ i.e. in $\bigcap_{k\geqslant M}E_k$; so in $E_\ast$. Conversely, $x\in E_\ast$ i.e. $ x\in \bigcap_{k\geqslant n}E_k$ for some $n=1,2,\ldots$ implies $x$ is in all but finitely many $E_m$, precisely, in all $E_m$ for $k\geqslant n$, except maybe the finitely many $E_1,\ldots,E_{n-1}$. I leave the proof for $E^\ast$ to you.
Comment: Ah, I had a bit of a problem with my logic. Thanks!!
Comment: Some authors say "ultimately" to mean "for all but finitely many".  I find this more elegant.

Infinitely Often vs Almost Always


Growth rate of primes of the form $a n+1$, with $n$ fixed

Question: If we fix a natural $n$, and let $a$ vary, how big can $a n + 1$ be before the first prime is encountered, in terms of $n$?  In other words, let $n = 32$.  Then, we have:
$$1(32) + 1 = 33 = 3 * 11 \text{ is composite}$$
$$2(32) + 1 = 65 = 5 * 13 \text{ is composite}$$
$$3(32) + 1 = 97 \text{ is prime}$$
The gist of the question is to try to find asymptotic bounds on $a$.  I believe that $a \in O(\log{(n)})$, and therefor $an+1 < c \cdot (n \log{(n)})$ for some $c$, but I'm not sure of this.  If this isn't the case, could someone please provide the correct bounds.
Comment: OEIS reference, which contains some further references: http://oeis.org/A034693
Answer: Let $ak+b$ be an arithmetic progression, $k = 1,2,3,\ldots$. Dirichlet theorem of primes in arithmetic progression says that number of prime $\le x$ which are of the form $ak+b$ is
$$
\pi_a(x) \approx \frac{\pi(x)}{\varphi(a)} \approx \frac{x}{\varphi(a)\log x}
$$
where $\varphi(n)$ is the Euler totient function. Hence heuristically, to get the first prime, we must have
$$
\frac{x}{\varphi(a)\log x} \ge 1
$$
or
$$
\frac{x}{\log x} \ge \varphi(a)
$$
which can be solved for $x$ for any given $a$.
Here is an approximate solution. Let $p_{\varphi(a)}$ be the $\varphi(a)$-th prime. Then, the smallest $x$ satisfying the above inequality is about $p_{\varphi(a)}$ which is about
$$
p_{\varphi(a)} \approx \varphi(a)\log \varphi(a) + \varphi(a)\log \log \varphi(a)
- \varphi(a)
$$
Then on a average the minimum value of $k$ is about
$$
\frac{\varphi(a)\log \varphi(a) + \varphi(a)\log \log \varphi(a)
- \varphi(a)}{a}
$$
Comment: An unconditional upper bound of the first prime in arithmetic progressions is given in Linnik's theorem. This states that there are constants $B, C>0$ such that the first prime $p_1$ in the arithmetic progression $p\equiv a \ \mathrm{mod} \ q$ satisfies $p_1\leq Bq^C$.
Comment: @SungjinKim: Looking at numerical data, $B$ would seem to be at least in the hundreds...  Is it true that $B$ is very large?  Wikipedia claims $C \le 5$.  If you could elaborate on this I would accept this as an answer, as it proves $p_1 \in O({p_1}^5)$, probably the best bound I could hope for.


Migrate media with alternative text

Question: I'm trying to import image with new media module on core 8.5.
I've a json source and on my .yml I've:
  field_media_image:
    target_id:
      plugin: migration
      migration: immagini
      source: fid

This works, immagini is another importer that imports files.
In the new media there is also an "alt" (mandatory) and "title" attribute on the media entity.
But if I try to add something like this, it doesn't work (alt_text is the correct source for alternative text). The media is created but is not referenced to the correct id:
  field_media_image:
    alt: alt_text
    target_id:
      plugin: migration
      migration: immagini
      source: fid

How should I pass the alt attribute to this field?
I also tried to use a syntax like:
  field_media_image:
    target_id:
      plugin: migration
      migration: immagini
      source: fid
  'field_media_image/alt': alt_text

But it doesn't work, the media is created but there is no reference to the correct id.
Answer: field_media_image/alt belongs in the immagini migration, not in the node migration.
In migration that creates the media item (destination plugin entity:media) you can map the media item's fields:
  # Image field see media_entity.bundle.image.yml.
  field_media_image/target_id: fid
  field_media_image/alt: field_file_image_alt_text/0/value
  field_media_image/title: field_file_image_title_text/0/value

  # Description field.
  field_description: field_image_description
  # Caption field.
  field_caption: field_caption

destination:
  plugin: entity:media

See https://www.previousnext.com.au/blog/migrating-drupal-7-file-entities-drupal-8-media-entities

Migrate media with alternative text


Google Colaboratory - Llama Index : Address already in use when trying to load Google Doc

Question: I'm trying to connect google collab using llama-index & openai library and google doc.
Following exactly the same example from the doc: https://llamahub.ai/l/google_docs .
The code I'm running, after installing libraries.
from llama_index import GPTSimpleVectorIndex, download_loader
OPENAI_API_KEY = "abc"

GoogleDocsReader = download_loader('GoogleDocsReader')

gdoc_ids = ['abc']
loader = GoogleDocsReader()
documents = loader.load_data(document_ids=gdoc_ids)

I uploaded the credentials.json file as recommended in the doc in:
/content/credentials.json

The credentials.json downloaded as explained in the doc https://developers.google.com/workspace/guides/create-credentials#api-key is structured as follow:
{"installed":{"client_id":"xyz.apps.googleusercontent.com","project_id":"myprojctId","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"abc","redirect_uris":["http://localhost"]}}

When I'm running the script I get the following error:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
in
17 gdoc_ids = ['abc']
18 loader = GoogleDocsReader()
---> 19 documents = loader.load_data(document_ids=gdoc_ids)
20 index = GPTSimpleVectorIndex(documents)

8 frames
/usr/lib/python3.9/socketserver.py in server_bind(self)
464 if self.allow_reuse_address:
465 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
--> 466 self.socket.bind(self.server_address)
467 self.server_address = self.socket.getsockname()
468

OSError: [Errno 98] Address already in use

I don't know what I'm doing wrong...
Answer: The problem is that llama_hub is using this Python code to authenticate against Google Drive:
/usr/local/lib/python3.10/dist-packages/llama_hub/google_docs/base.py
 flow = InstalledAppFlow.from_client_secrets_file(
                    "credentials.json", SCOPES
                )
                creds = flow.run_local_server(port=8080)

As you can see, the code tries to open a local server listening in tcp/8080. I think that it is needed for completing the OAuth incantation (a callback URL). But either that port is already binded or it is not possible to do that in Colab. I ended up running the code locally. Once you do it locally, you'll get a token.json file that you can upload to Google Colab and continue from there.


Studying artists like Erroll Garner, Oscar Peterson, Monk - how can I improve in this style

Question: I am currently taking jazz piano lessons from a jazz pianist. I am very fascinated by this music style, and listen to it a lot. I found out that I really like the traditional kind of jazz piano, especially Erroll Garner.
The problem is: my piano teacher is more of a modern kind of jazz player. He knows a lot of stuff about Herbie Hancock, Chick Corea, those kind of artists. He said to me that he doesn't know a lot of things about traditional piano, so my question is: how can I, besides listening to a lot of traditional jazz piano, become better in that style?
Are there ways to learn more about traditional theory, or certain things I need to know to begin in that direction? Btw, I can't read music.
Answer: I would suggest transcripts of solos, but...

Btw, I can't read music.

Oscar Peterson wrote a series of jazz etudes for beginners.
I've never played them and I don't know if any jazz teachers use them, but at least they are straight from the source.
According to the NPR bio Monk could read and studied classical piano.
And according to this other NPR bio Garner could not read.
So it's a bit of a mixed bag with the icons you want to emulate whether they could read music. You might consider whether your ability to read and your knowledge of classical repertoire and techniques are important for your own goals.
Comment: @AlbrechtHügli, I agree those studies don't seem to exemplify Peterson's own style. But I'm trying to show the OP that *not being able to read music is a problem*. And it doesn't matter if the style is jazz. The fact that the OP won't be able to benefit from the *written transcriptions* of these artists is a huge learning barrier.
Comment: I've looked at this studies some years ago but  I couldn't find a great difference to any  other boogie or blues books for beginners. I don't think this is somehow  it's not a introduction in his style.
Comment: I fully agree! that's what I say. and I hope all beginners have heard it.
playing boogie patterns can also  be a good help for learning to read.
Answer: You might want to take a few lessons with other teachers in your area to see if you can find someone with more experience with the kind of music you like. If you have a good relationship with your current teacher, you may even ask him if he knows of anyone.
There is nothing wrong with trying out teachers to find the best one for you, and you don't even have to stop studying with your current teacher, if you find you're getting benefit from him. Some supplementary lessons from someone else can give you a whole new perspective.
Additionally, transcribing (learning by ear) some of your favorite Erroll Garner solos will also be very beneficial.
Comment: I had to transcribe the oscar peterson video by emmie nolten (look up my answer) for really understanding what she  explains.
 of course there are people who are learning by listening and others reading and analyzing, but I agree that both approaches are needed. but I will never accept the argument: I can't read.
Answer: Even I know that you  are not the only jazz musician who can't read music, I conclude of your answer that purchase this competence will help you the most!
You will be able to play sheet music and the writings of your favorite composers. You can find some books for free download or on scribd. You will be able to study the theory book of Mark Levine and the music theory of classic music.
Otherwise you well always stay dependent of youtube tutorials (which also have a great benefit to you. If you can't find them I will post you some links. I like to watch Amie Nolte e.g. She does really well!

I'd like to add another video:
Comment: Amie Nolte is a good teacher, but I would say she's more towards the modernist camp, so maybe not the best for the OP.
Comment: yes,  she is the most beautiful girl and I love her a lot ;)


For $T $ a continuous, linear, open map there exists a $C$ such that $||x|| \le C||Tx|| $

Question: As stated in the title, let be a $T $ a continuous, linear, open map from a normed space $X$ onto a normed space $Y $. I would like to know if it is true that there exists a constant $C$ such that for any $x \in X, \ \ ||x||_X \le C||Tx||_Y $.
I tried to verify it but got stuck. Is the claim true?
Answer: Of course, if such a constant exists, we must have $C>0$. And $T$ must be injective; otherwise, there will be a non-zero vector $x$ such that $Tx=0$ and so $\lVert x\rVert>C\lVert Tx\rVert=0$.
On the other hand, suppose now that $T$ is injective. Since $T$ is open and linear it is surjective. So, since $T$ is injective too, it has an inverse. Let $C=\lVert T^{-1}\rVert$. Then$$\lVert x\rVert=\bigl\lVert T^{-1}(Tx)\bigr\rVert\leqslant C\lVert Tx\rVert.$$
So, such a constant $C$ exits if and only if $T$ is injective.
Comment: Now, you are **not** being dense. I did not express myself clearly. I shall edit my answer.
Comment: Done. What do you think now?
Comment: Looks good!  ${}$


Does the bass always have to harmonise with the lead?

Question: I have written a half decent lead, at least for my level, and I am now trying to harmonise a bass with it. I am employing one of the most basic kind of methods to achieve this - playing the root note of the lead with the bass, to harmonise it with the lead. Well, actually I read that this method is used with chords (where it would be the root of the chord, not the scale), though I am only writing a monophonic lead, (i.e no chords) for now, since I am just starting out.
These are my lead and bass notes:
Lead (Portato):         Bass(legato):        Harmonic value:
C  *2         C                          Perfect consonance
A# *1         C                          Weak Dissonance
G  *3         C                          Perfect Consonance
F  *2         F                          Perfect Consonance
E  *1         F                          **Strong Consonance**
C  *3         F                          Perfect Consonance

I think an image is in order:

A few things:
1. The bass is two octaves below the lead.

2. That white bar before the red is only to show that the two bars are separate by the way, it's hard to see otherwise :)

3. Also note (haha, get it, note?), that the notes do vary, but the set up is configured to display the notes all on the same line to show which notes come from what sound at any given time.

So what am concerned about is the notes of E coming from the lead, and the note of F coming from the bass, it doesn't sound out of place at the time (remember that the bass is played legato), but this is really just for future reference in case say, half the notes don't harmonise well. Also, I have no idea what the implications of this may be if I was to try and apply EQ, or add certain effects, and so on.
Since bass lines are usually grounded, in that they are played smooth and constant, where leads are pretty much the opposite, I wonder what the status quo is when it comes to harmonisation. Are there any rules of thumb? How strict should we follow the rules of harmonisation in respects to basses and leads?
One thing I notice is that there seems to be less and less dissonance as we play notes further and further apart, even when purposely playing only two notes which would be very dissonant within the same octave, such as E and F#, to a certain degree, even E and F.
My personal though by no means professional theory, is that the lower the pitch of a note note X, the less sidebinds there are, thus leading to neither consonance or dissonance.
Thanks for reading my post, it's very much appreciated! :)
Comment: In my mind, if the bass and the lead don't sound good together, the lead is more likely to be seen as the incorrect note, not the bass. I think the music term for sidebands are sum and difference tones. Also, I wouldn't get too hung up on the technical analysis. If it sounds good then it is good.
Comment: I'm not sure what you mean by "sidebinds".  By widening the gap between pitches, you're lowering the beat frequency.  Eventually it gets slow enough that it's not really noticeable.  Regarding your title question: No.  As for rules of thumb: What style of music are you writing?
Comment: Hey, am not really sure what style am writing for, am just beginning. Although, my main focus now is dance music, which, from what i've read, includes dubstep, house, pop, and other such genres. Also known as EDM, electronic dance music. What sidebands are doesn't really matter by the way, my little theory was really just a side note (though the term is a real and technical term though, used in timbral analysis, or acoustic analysis)
Comment: One very common way in which the bass and melody will diverge is through the tritone substitution. Say the chord progression is Dm7 - G7 - C, with the melody going C - B - C. The bass may elect to play the tritone subbed version -- Dm7 - Db7 - C -- and play the notes D - Db - C. Db is very much not in a G7 chord, yet the harmony works just fine.
Answer: There is no "have to" in music. There are common patterns and conventions, but the only rule is, if it sounds good, it is good.

it doesn't sound out of place at the time

... and therefore it's OK.

I have no idea what the implications of this may be if I was to try and apply EQ, or add certain effects, and so on

EQ generally has very little effect on harmony concerns. The only exception I can think of is if your EQ filtered out the frequency range that gave a particular instrument pitch -- in this case it would hide any harmony/pitch problems.
Time based effects like delay could end up placing two pitches together which clash. Worry about it when it happens, and use your ears.

Sometimes discord works. Sometimes you want nothing but harmony; it depends what you're going for.
Two concepts that may be useful are "passing notes" and "resolution".
A "passing note" is a note within a sequence of notes, which leads from one note to another. It's pretty common for passing notes not to harmonise, but you don't stay on them for long, so nobody worries about the discord.
"Resolution" is when music hangs on a discordant combination of notes -- or some sound which otherwise causes "tension" in the listener, then returns to a "comfortable" combination of notes, releasing or "resolving" the tension. For example, a song in C major might end on a C13 chord, held for a bar, then going back to a nice clean C major.
Comment: Hey slim. So basically what I get from this is that 1. Passing notes are only exceptions, in that most notes in the bass will harmonise with the lead. B. Even if so, it is the resolution to the tonic that people enjoy anyway, thus dissonance isn't to be avoided completely, since otherwise there may be no resolution.Though, harmonisation is still preferable right? In that even though passing notes may not be a problem, if half or more of the notes clash, would this be a problem? What's considered too much dissonance? By the way, I really appreciate your answer, thank you for your guidance :)
Answer: "Harmonize" does not mean "consonance." That's important for really understanding your question.

Does the bass always have to harmonise with the lead?

If "harmonize" was meant to mean "consonant", then no, the lead does not always need to be consonant with the bass.
The essential meaning, the historic meaning of "harmonize", is to combine parts in a musical way. That's pretty wide open for what "harmonize" and "musical" mean in technical terms. But, in the terms that you posted - "perfect consonance", "strong consonance", "weak dissonance" - all of those and more may be present in well harmonized music.
In that sense, yes the lead should always harmonize with the bass, meaning you always want the lead to work musically with the bass (excepting avant-garde styles.) That harmonization may include very conspicuous and expressive use of dissonance.

Are there any rules of thumb?

Yes. But it is the study of harmony and counterpoint. Those topics are too broad to cover is a Q&A format.
However, if we just stick to the broad consonance/dissonance aspect, you could come up with some practical guidelines:

Make melody progress step-wise through scale tones or skips outlining triad chords (keeping the melodic range within a octave or a twelfth is practical for singable lines.)
In terms of chords, major and minor triads are the basic consonant harmonies.
Using consonances on strong beats generally creates musical stability.
Using dissonances - including on strong beats - creates instability and dramatic tension. Dissonance off the strong beats can be called unaccented dissonance, and placing dissonance at unaccented points is a common approach, but not a requirement, in tonal music.
When there is a dissonance between the bass and lead moving one of those voices by scale step to form a consonance will resolve the dissonance "smoothly."
The ebb and flow of consonance and dissonance creates forward impulse and movement in music.
You're free to use chromatic tones or change the scale, generally consider those changes to be be destabilizing, similar to the destabilizing effect of dissonance, which can be exploited for expressive effect. Sticking to the diatonic tones of a scale will generally have a stabilizing effect.

This rules of thumb list is my own creation, but it is based on common ideas and procedures found in harmony and counterpoint textbooks. It makes no rules about chord root progression and relative motion so you should be able to apply it to a lot of different styles. It's really just a simple framework for thinking only in terms of consonance and dissonance.

...One thing I notice is that there seems to be less and less dissonance as we play notes further and further apart

That seems to be particular to that software. You would need to know what it's calculating to say more.
Dissonance/consonance is usually stated objectively in terms of pitch ratios, where 1:1 - a unison - is the perfect or most consonance you can have, and the rest is just an infinite spectrum of greater and greater dissonance.
Generally, the lower an interval is played the "muddier" it will sound. C2 E2 will sound muddy compared with C4 E4 (the numbers indicate octave.)
IMO widely spaced dissonances seem less harsh than closely spaced dissonances.
In both cases I think this is more about acoustics and overtones than pitch ratios of the fundamental pitches. Low range intervals have messier overtones. Closely spaced dissonances have noticeable beating. I don't really know acoustics, so I can't give a good explanation. Aesthetically the two points are easily perceived.
Answer: A general principle for bass in most current popular forms of music is that "the bass should play chord tones on strong beats". Strong beats are typically the 1 and 3, and in addition, there is a strong tendency to play the root of the chord on the 1.  Doing this is the most straightforward way for the bass to perform it's dual role of harmonic and rhythmic foundation.
In order to determine which chords your melody is implying you'll either need a good ear, or an analysis of the notes that comprise the melody.
There are various ways to stray from this general principle, since uniformly conforming to it can sound tired.  A good example is adopting a "one-drop" rhythm where the bass does not play on the one; since this comes from Reggae music, it often lends that flavor, or is appropriate in the context of that kind of music.
However, being aware of the general idea that the bass should play chord tones on the the 1 and the 3, and when you choose to deviate from it
Comment: Ah, I see, so what you provide is guidelines with which one can deviate from, if it would work in their favour.  I like the safety that such guidelines offer since when one is uncertain on the course of action, then at least there's some solid grounding with which one can stand. Say, is there a resource out there with other such guidelines? Thanks a lot by the way :)
Answer: In general, the bass line needn't be continually consonant with the melody, but it should support the melody. The bass and melody should make good (not "strict") two-part counterpoint with the melody. One may wish to avoid parallel fifths and octaves (so as not to sound like the bass quit playing) but some dissonance can be useful.
Answer: You are going to need at least some very minimal piano skills, knowing a few scales, etc. You can find these online.But an electronic dance track should be able to pack the floor with just the bassline and drums.
You really should start by focusing in your favorite of these genres and build a library of music. Then you need to start listening to them constantly and chart out what beats the various "signature" drum sounds appear on, e.g. 808 hand claps always come on an upbeat, in house the kick drum is typically on the 1, 2, 3, & 4. Then make your own beats based on your findings.
Then you write lines that have a catchy rhythm that isn't identical to the drums, but accents on the correct beats. Hip hop beats accent on 2 & 4, for instance. Refer to your notes. Until you get a handle on some theory, just raise or lower the pitch of the whole repeating lead pattern until it sounds good over the bassline.
If you are actually a fan of some other genre, learn that. Don't do dance music because you think its easy, if your heart isn't in it it will be a chore. If you love it, you'll get the hang of it soon enough.
And read the British magazines they are about 1000x as useful.
Comment: This answer seems unrelated to the question. Was the question heavily edited after you posted this?


Azure ML - Import Hive Query Failing - Hive over ADLS

Question: We are working on Azure ML and ADLS combination. Since HDInsight Cluster is working over ADLS, we are trying to use Hive Query and HDFS route and running into problems.
Request your help in solving the problem of reading data from hive query and writing to HDFS. Below is the error URL for reference:
https://studioapi.azureml.net/api/sharedaccess?workspaceId=025ba20578874d7086e6c495cc49a3f2&signature=ZMUCNMwRjlrksrrmsrx5SaGedSgwMmO%2FfSHvq190%2F1I%3D&sharedAccessUri=https%3A%2F%2Fesprodussouth001.blob.core.windows.net%2Fexperimentoutput%2Fccf9a206-730d-4773-b44e-a2dd8c6e87b9%2Fccf9a206-730d-4773-b44e-a2dd8c6e87b9.txt%3Fsv%3D2015-02-21%26sr%3Db%26sig%3DHkuFm8B2Ba1kEWWIwanqlv%2FcQPWVz0XYveSsZnEa0Wg%3D%26st%3D2017-10-16T18%3A31%3A06Z%26se%3D2017-10-17T18%3A36%3A06Z%26sp%3Dr
Answer: Azure Machine Learning supports Hive but not over ADLS.


is it possible to have a c# generic method that return different object with same fields?

Question: I have two identical classes but in different namespaces, is it possible to use a generic method to instantiate and populate one object or the other?
namespace ns1{
   //.....

    public class class1{
        private string name;
        public string name{
            set{this.name=value;
        }
    }
}

namespace ns2{
    //....

    public class class2{
        private string name;
        public string name{
            set{this.name=value;
        }
    }
}

I've tried something like this, but in this way, the type of T is not recognized like the field "name" because T is an object:
class1 cl1 = getMyclass<Class1>("Daniel");

class2 cl2 = getMyclass<Class2>("Daniel");

private T getMyClass<T>(string name) where T : new()
{
    T tclass = new T();
    tclass.name = name;  // ***THIS IS NOT POSSIBLE***

    return tclass;

}

Answer: You can introduce and interface
public interface INamed
{
    string Name { get; set; }
}

Your classes should implement this interface
public class1: INamed { ...
public class2: INamed { ...

And your method should have generic constraint of the interface
private T getMyClass<T>(string name) where T : INamed, new() { ...

Comment: As stated in my answer, it may not be possible to introduce an interface. For example when the classes from different namespaces are in 3rd-party code.
Answer: You can define an interface or base class, implement it in your classes, and use the interface/base class to constrain the generics.
interface IHaveName
{
  string Name { get; set;}
}

class Class1 : IHaveName
{
   ...
}

private T getMyClass<T>(string name) where T : new(), IHaveName

Answer: Solutions with interfaces are probably your best option, but it is possible to do it without introducing an interface (which may not be possible in your case), namely with dynamic:
private T GetMyClass<T>(string name) where T : new()
{
    dynamic tclass = new T();
    tclass.name = name;
    return tclass;
}


Não se pode usar onclick em uma option de um select?

Question: Tenho um script que ao clicar em uma option especifica chamaria uma função no javascript com onclick, mas esse script só esta funcionando no firefox desktop nos demais navegadores não funciona, venho desconfiando que o problema etá sendo causado por estar usando onclick nas options, existe alguma forma alternativa de eu conseguir o desejado sem utilizar o onclick?, realmente não se deve usar o onclick em uma option de select?
Meu select:
<select class="custom-select" name="tamanho" id="tamanho" required="required">
        <option selected value="Nenhum">Escolha...</option>
        <option value="G" onclick="mostraG()">Grande (G)</option>
        <option value="M" onclick="mostraM()">Média (M)</option>
      </select>

Meu JS:
// Mostra M e oculta G
function mostraM(){
    if (document.getElementById('pizzaM').style.display == "none"){
        document.getElementById('pizzaM').style.display = "block",
    document.getElementById('pizzaG').style.display = "none",
    $("#sabor1G").val("Nenhum"),
    $("#sabor2G").val("Nenhum"),
    console.log("WORK");
    }
}
// Mostra G e culta M
function mostraG(){
    if (document.getElementById('pizzaG').style.display == "none"){
        document.getElementById('pizzaG').style.display = "block",
    document.getElementById('pizzaM').style.display = "none",
    $("#sabor1M").val("Nenhum"),
    $("#sabor2M").val("Nenhum"),
    console.log("WORK");
    }
}

Comment: Já tentou com `$('#tamanho').on.('change', function(){})`
Comment: Poderia me mostrar um exemplo?
Comment: Sim. Um momento
Comment: O que realmente precisa que seja realizado no seu select? Se deseja executar uma função quando cada opção é selecionada a melhor opção é onchange no select.  https://pt.stackoverflow.com/questions/365402/gostaria-de-saber-como-receber-o-valor-do-meu-select-ao-clicar-em-um-option-com/365408#365408
Comment: https://pt.stackoverflow.com/questions/238457/como-ativar-um-onchange-que-utiliza-options-de-um-select-via-javascript
Answer: Voce pode fazer assim:

$('#tamanho').on('change', function () {
  let value = $(this).val()

  if (value == 'G') {
    mostraG()
  } else {
    mostraM()
  }
});

function mostraM() {
  console.log("mostraM");
}

function mostraG() {
  console.log("mostraG");
}

<select class="custom-select" name="tamanho" id="tamanho" required="required">
        <option selected value="Nenhum">Escolha...</option>
        <option value="G" >Grande (G)</option>
        <option value="M" >Média (M)</option>
</select>
Answer: Você pode usar o  $('#tamanho').on('change', function(){ para escolher a opções
Olhe o exemplo

$('#tamanho').on('change', function(){
  const value = $(this).val()
  if( value == 'Nenhum' ){
     nenhum()
  }
  else{
    if( value == 'G' ){
       mostraG()
    }else{
      mostraM()
    }
  }
})

const mostraM = () =>{
   $('.pizzaM').fadeIn()
   $('.pizzaG').fadeOut()
}

const mostraG = () =>{
   $('.pizzaM').fadeOut()
   $('.pizzaG').fadeIn()
}

const nenhum = () =>{
   $('.pizzaM').fadeOut()
   $('.pizzaG').fadeOut()
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

<select class="custom-select" name="tamanho" id="tamanho" required="required">
        <option selected value="Nenhum">Escolha...</option>
        <option value="G" >Grande (G)</option>
        <option value="M" >Média (M)</option>
</select>

  Pizza M

  Pizza G

Espero que ajude


Beginner help at proving two sets are equal

Question: I'm a computer scientist who is a complete noob at proofs.
This was a part of my home exercises but I think I failed totally so I'd love to have some advice how I'm supposed to do this. It's about propositional logic.
The question is:

Let $M$ be the set of all possible valuations. For each propositional formula $A$, define the set
$$[A]=\{v\in M\mid v(A)=1\}.$$
  That is, $[A]$ is the set of all valuations which make the formula $A$ true. Show that:
$$[A\wedge B]=[A]\cap[B]$$

My proof:

Let $x∈[A∧B]$. Therefore $x∈A$ and $x∈B$.
  Let $y∈[A]∩[B]$. Therefore $y∈A$ and $y∈B$.
  Therefore $x$ and $y$ are equal thus the sets are the same.

I think I skipped over some crucial steps like defining the set but for the love of god I can't understand how these proofs work. If someone could strip away all the magic from this and explain it in a way that a pragmatic programmer could understand it I'd be forever grateful. The abstraction level here is just too great for me to figure out the "syntax".
Like for example I can't understand with what set of rules should I establish my deductions? Intersection of sets I guess is so common property that every mathematician is supposed to know it (?) or do I have to reference the law which I'm this conclusion basing? That would at least make sense to me. Eg. "By the rules of set theory intersection of two sets is x and x". Sure a bit wordy but that would finally clear this thing up for me.
I understand axioms are the core properties of the objects and from which all laws/rules deliver from (?) but is it always somewhat assumed that the reader knows those rules/axioms? I wish I could just run this in my code interpreter to see if it's correct or not... :)
Thank you in advance!
Comment: You're just writing down symbols that don't mean anything.  You say for example, that if $x \in [A \wedge B]$ then $x \in A \cap B$.  That doesn't make any sense.  You mean  $x \in [A] \cap [B]$ but it's not a matter of "syntax" or "magic".  Anyone can write what you did accidentally, but that you can't see what's wrong indicates that you don't understand what the formulas mean.  Can you explain in words what $x \in [A \wedge B]$  means?
Answer: Usually the easiest way to show that two sets are equal is to show that each one is a subset of the other.  A common proof format is as follows.

Let $x\in LHS$.
    ...
    Therefore $x\in RHS$.
    Conversely, let $x\in RHS$.
    ...
    Therefore $x\in LHS$.
    We have shown that $LHS\subseteq RHS$ and $RHS\subseteq LHS$, therefore $LHS=RHS$.

In your case I think you are assuming too readily the relation between $\wedge$ and $\cap\,$.  Try this.
Let $v\in[A\wedge B]$.
Then by definition $v(A\wedge B)=1$.
Therefore $v(A)=1$ and $v(B)=1$.  $(*)$
Hence $v\in[A]$ and $v\in[B]$.
By definition of intersection, $v\in[A]\cap[B]$.
Thus $[A\wedge B]\subseteq[A]\cap[B]$.
In line $(*)$ you may need to fill in some details depending on exactly what you have been taught about valuations.  You will also need to prove $[A]\cap[B]\subseteq[A\wedge B]$.  Give it a try.
Good luck!


Android Application for money handling

Question: I am planing to create a android application for doing some banking operations like fund transfer and all, but I fear the security of the application. Doing some research I found that <code>"128-bit SSL protection"</code> is the best way to protect mobile application. But I dont know any thing about that 128-bit SSL protection. Can any one tell me how I can implement this? and what are the other perfect ways to ensure the security of the transactions. Please give your valuable suggestions.
Answer: You need to implement SSL(HTTPS) to your App.
You need to follow this doc : http://developer.android.com/training/articles/security-ssl.html
Also,i hope this may help :
Android application with SSL
Comment: yes i had worked for a bank for around 2 years ...did a bit of RnD on 2-way SSL and kind-of even implemented it too for the web interface ... just follow the links i have provided you will surely get leads to how to go about doing it ...
Comment: thank-you for the quick response and i will check this, in the mean time can i ask you that do you have any experience in banking apps.

Android Application for money handling


How to let the user fill in the "Recipient" field of the contact form?

Question: I created a new type of contact form. It is called "Invitation".
The problem is that the recipient field does not appear and it is not editable.
I want the user to fill in the recipient's email to send invitations.
How to let the user fill in the "Recipient" field of the contact form ?
Comment: Not sure if the "contact form" functionality is a proper fit for an invitation form.
Comment: @baikho Why can't the contact form do this? I just need to edit the "Recipient" field and create a TWIG template to create an invitation email. The user fills in the destination with an address and clicks "Send".
Comment: Maybe have a look at the Webform module to build your own contact form the way you need it. I think it already comes with the option to submit the form to an email address from user input (which could be a select, radios or just a textfield I think).
Comment: Another alternative would be to provide your own custom module to alter the contact form and the submit function.
Comment: This contact form will be unique and accessible by authenticated users and with a special role
Answer: The recipient isn't a Drupal field so I don't think this can be done without custom coding.
This is probably to guard against using the form for spamming. If the recipient field were accessible to anonymous users, then anyone could use the form to send unsolicited emails.


Change default Taxonomy value on form via form alter in D7

Question: I am trying to alter a form with a taxonomy term select drop down field; I want to change the default term selected when the form loads.  I'm altering the form array via hook_form_alter; however, my changes do not seem to be taking effect.  I'm looking for an answer similar to this but for Drupal 7.
I'm expecting :
<code>        $form['field_mytax_reference']['#default_value'] = array($taxTermId => $taxTermName);
</code>
to do the job but the form remains with the default specified when the field was created.
Thanks in advance.
Answer: It'll be something more along the lines of:
<code>$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = $taxTermId;
</code>
If the field is a multi-select you would wrap the default value in an array, but there's no need to set a key for it:
<code>$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = array($taxTermId);
</code>
Have a look at Why is hook_form_alter() so messy? for a bit more info.
Answer: This worked:
<code>$form['field_mytax_reference']['und']['#default_value'] = array($term_tid);
</code>
Clive's answer was a helpful point in the right direction.


Why use average_precision_score from sklearn?

Question: I have precision and recall values and want to measure an estimator performance:
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import auc, average_precision_score

y_true = np.array([0, 0, 1, 1])
y_scores = np.array([0.1, 0.4, 0.35, 0.8])

precision, recall, threshold = precision_recall_curve(y_true, y_scores)

plt.figure()
plt.plot(recall, precision)
plt.show()

But there is 2 related metrics: sklearn.metrics.auc and sklearn.average_precision_score:
print(auc(recall, precision))
print(average_precision_score(y_true, y_scores))

0.7916666666666666
0.8333333333333333

It seems that average_precision_score would over-estimate AUPRC. So what is the point to use average_precision_score?
UPDATE
I do not agree, that the question is closed. Linked question does not answer on this:
Why AUC under PR curve is less than average_precision score, while one of the arguments against trapezoidal rule is
"This implementation is not interpolated and is different from computing the area under the precision-recall curve with the trapezoidal rule, which uses linear interpolation and can be too optimistic."
So is trapezoidal rule optimistic or pessimistic?
Answer: The average precision directly emphasizes the ability to distinguish between positive and negative examples, whereas area under the precision recall curve (auc) gives an overall measure of performance across all possible classification thresholds.
The average precision score would be more suitable when dealing with imbalanced datasets as it focuses on the positive class being predicted, which is usually the one of interest in an imbalanced scenario.  Auc considers both the positive and negative class, which wouldn't helpful if the negative class is significantly larger.


Erro C# System.IndexOutOfRangeException

Question: Boas com uma duvida neste codigo , ele na linha 14 da me um erro como podem ver na foto ...
Soluções ??
Obrigado
Codigo:
using System;
public class Exercise052
{
    public static void Main()
    {
        Console.Write("Cuantos datos reservo: ");
        int repeticiones = Convert.ToInt32(Console.ReadLine());
        float numero;
        float[] listaNumeros = new float[repeticiones];

        for (int i = 1; i <= repeticiones; i++)
        {
            Console.Write("Dime numero {0} para guardar en la lista: ", i);
            listaNumeros[i] = Convert.ToSingle(Console.ReadLine());
        }

        Console.Write("Que numero comprueba en la lista? ");
        numero = Convert.ToSingle(Console.ReadLine());

        while (Console.ReadLine() != "end")
        {
            for (int i = 1; i <= repeticiones; i++)
            {
                if (listaNumeros[i] == numero)
                    Console.WriteLine("El número {0} existe en la lista", numero);
            }
        }
    }
}

Comment: Qual é o erro? Escreva na pergunta. Não use imagens.
Comment: O erro que aparece é "  System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"
Answer: O erro na verdade não é no Convert.ToSingle() e sim no seu laço de repetição. Os indices de um array começam no 0 e não no 1, então quando chegar na ultima iteração vai dar o erro System.IndexOutOfRangeException: Index was outside the bounds of the array., ou seja, o indice estava fora dos limites do vetor.
Se o vetor tem 5 posições por exemplo, a primeira posição é o 0 e a última é o 4.
Para corrigir seu algorítmo, você deve trocar o seu for por:
for (int i = 0; i < repeticiones; i++)
{

}

Comment: Tem toda a razão , eu estava a executar o programa antigo... Peço desculpa e obrigado por me ajudar.
Comment: Troquei o código e continua o mesmo erro .Mas obrigado pela resposta se tiver outra possivel hipotse agradecia.
Comment: O erro continua na mesma linha?
Comment: Sim , infelizmente
Comment: Testei o código no repl.it e funcionou perfeitamente. O link é este: https://repl.it/@natanfernandes1/WellmadeIllfatedProfiles

Erro C# System.IndexOutOfRangeException


Search index only part of custom content type

Question: If I add a search index  display on all my custom types, and set visible only a few columns, those columns will only be included in the search index ?
My problem is that i have columns i don't want to index (like file names), and i don't know how to do it.
Comment: I think this is a dup, but I can't find it right now.
Answer: The search index is a view mode, but it is hidden by default (for some unknown reason).
Goto the Manage Display page for your content type.  Expand the Custom Display Settings at the bottom.  Tick Search Index and save.
A new tab, Search Index will appear.  Click this, and then configure your content type to show / hide the fields you want indexed.
You may need to dump the search index (admin/config/search/settings) and then reindex the site.  I can't recall if saving the search index does this automatically, of if I normally form alter that form to do it.  The easiest way to do this is with drush:
drush -y search-reindex
drush -y search-index

As a side note, I will be releasing a small module to help debug search issues and check things like this.  I am test driving it on a few sites now, and think it will be ready soon.
Comment: @rhose87 Yes, that should work for you.  I will update the answer if/when I release the module.
Comment: So, if i enable the `search index` display view and set it how i want, only what i set visible will be indexed ?


What is the distribution of values for the expression x * y + (1-x) * z, for x,y,z in [a, b]?

Question: Let $X$, $Y$ and $Z$ be random variables with probability distributions $f_X, f_Y, f_Z$ taking values in the unit interval $[0,1]$. I'm interested in the distribution of
$$X\cdot Y + (1-X)\cdot Z,$$
which always again takes values in $[0,1]$.
Below we see a histogram of samples for $X,Y,Z$ uniformly distributed (and it reminds me of some Shannon entropy function).

It turns out that the distribution of $X\cdot Y$ with two variables is already tricky enough to compute, see Wikipedia, and no literature I found was for the unit interval. Okay so now let's first focus on that two-variable question and even assume uniform distributions of $X$ and $Y$, then I expect I gotta compute something along the lines of
$$\int^x 1 \int^{z/x} 1 \,{\mathbb d}y \,{\mathbb d}x $$
I left out the lower bound $0$ because this makes problems with the log. I suppose my first much reduced question would thus be this one:
Let $X$ and $Y$ be random variables with probability distributions $f_X, f_Y$ taking values in the interval $[\epsilon, 1]$. I'm interested in the distribution of
$$X\cdot Y,$$
which takes values in $[\epsilon^2, 1]$?
In this thread such a question is asked an Mathematica is used to give a few expressions involving logs of $z$. I can imagine the result to be something along the lines of $a-b\,\log(z)$ but I'm not sure why $z$ would make it into the nonlinear expression given the above kind of integral.

Assuming we find this, how do deal with the limit $\epsilon \to 0$? And then, for the 3 variable case, we might have to go back to the definition for the mulivariate distribution case (Wikipedia) but I first need to get the $\log$-issue above.
This StackExchange question discusses the case of $n$ uniformly distributed variables, with values in $[0,1]$,for large $n$, in which case we get a Gaussian.
Answer: If $X,Y$ are independent random variables uniformly distributed on $[0,1]$, then for every positive measurable function $f$ we have
$$\eqalign{E(f(XY))&=\int_0^1\int_0^1f(xy)dxdy=
\int_0^1\frac{1}{y}\int_0^yf(t)dtdy\cr
&= \int_0^1f(t) \int_t^1\frac{dy}{y}dt\cr
&=\int_0^1f(t)\ln\left(\frac{1}{t}\right)dt
}$$
So, the desity function of $T=XY$ is
$f_T(t)=\textbf{1}_{(0,1)}(t)\ln(1/t)$.
Similarly, if $X,Y Z$ are independent random variables uniformly distributed on $[0,1]$, then for every positive measurable function $f$ we have
$$\eqalign{E(f(XY+(1-X)Z))&=\int_0^1\int_0^1\int_0^1f(xy+(1-x)z)dxdydz=
\int_0^1\int_0^1\frac{1}{y-z}\int_z^yf(t)dtdydz\cr
&=2 \int_{y=0}^1\int_{z=0}^y\frac{1}{y-z}\int_z^yf(t)dtdydz\cr
&=2 \int_{t=0}^1f(t)\int_{z=0}^t\int_{y=t}^1\frac{dy}{y-z}dydzdt\cr
&=2 \int_{t=0}^1f(t)\int_{z=0}^t\big(\ln(1-z)-\ln(t-z)\big)dzdt\cr
&=2 \int_{t=0}^1f(t)\Big[-(1-z)\ln(1-z)+(t-z)\ln(t-z)\Big]_{z=0}^{z=t}dt\cr
&=2 \int_{t=0}^1f(t)\big(-(1-t)\ln(1-t)-t\ln(t)\big)dt\cr
&=2 \int_{t=0}^1f(t)\ln\frac{1}{(1-t)^{1-t}t^t}dt\cr
}$$
So, the desity function of $T=XY+(1-X)Z$ is
$$f_T(t)=2\textbf{1}_{(0,1)}(t)\ln((1-t)^{t-1}t^{-t}).$$
A plot of this density function can be found here.


I want to increase the KVM root file system from 60GB to 160 GB

Question: The KVM image file 3.1GB in the file system on the hypervisor. The file systems are only showing up at 60 GB with df -kh total space. I want to increase the KVM volume space to 120 GB. I tried 'virsh blockresize'. It says its unsupported?
file format: qcow2
virtual size: 160G (171798691840 bytes)
disk size: 3.0G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: true
refcount bits: 16
corrupt: false
How do I increase the KVM volume space size so I can increase root and allocate other logical volumes/file systems.
Comment: You don't need to increase the file size. Instead, the filesystem inside the VM has to be modified. But, as Michael already has been written, please tell us more.
Comment: Please show exactly what you did instead of a vague description.
Comment: The image size in /var/lib/libvirt/images is showing 3.1G. The qemu-img info size is showing 160 GB for the virtual size. A df -kh is showing a 60 GB file system. I want to add 100 gb to the root volume so I can increase the root file system size to 120 GB. I need to know how I do that. I have tried google fu to find the answer. I haven't found it.
Answer: Your output from qemu-img above shows the disk image exposed to the guest already offers '160 GB', of which the guest OS has only written data into 3 GB.
So if your guest OS is only reporting '60 GB' free, it suggests the problem lies in the way the guest OS is using the disk. Likely either the guest partition table layout needs to be extended or filesystem needs to be extended, or both.


restrict profile field to module and admin in drupal 6

Question: I am using profile for storing some more information for users. but I want one field of profile be only editable by administrator and my own module code and viewable by own user and administrator.
I guess I have to set visibility of field to '  Hidden profile field, only accessible by administrators, modules and themes. '
but I don't know if it is right or not.
Thank you.
Answer: Yep, you got it right.
Inside the profile.module's profile_view_profile() function, it uses the following logic when modifying $user to include the additional fields for viewing...
// Show private fields to administrators and people viewing their own account.
if (user_access('administer users') || $GLOBALS['user']->uid == $user->uid) {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);
}
else {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND visibility != %d ORDER BY category, weight', PROFILE_PRIVATE, PROFILE_HIDDEN);
}

...so yes, settings fields to PROFILE_HIDDEN will show them only to users with the administer users permission and/or to the user who is viewing his/her own account.
When editing a user, the module calls upon the _profile_get_fields() function to present the fields to be edited on the resulting form, and there, it uses the logic...
if (!user_access('administer users')) {
  $filters[] = 'visibility != %d';
  $args[] = PROFILE_HIDDEN;
}

...to restrict the editing of these fields to just users with the administer users permission by filtering out those fields from users without that permission.
And, of course, if your module or theme wants to edit anything in the database directly, there is nothing to really stop it.
Comment: If I want to change the hidden value by module when user is not logged in I have to change it directly in database?
Comment: the only users that can edit/change a `PROFILE_HIDDEN` via the form are ones with `administer users` permission;  a or your module should be able to change anything it wants programatically.


Comparing the kernel's net.ipv4.ip_local_port_range setting to a webserver's port setting

Question: Being new to webservers, I need to clarify a concept. Apologies if this is a less-than-stellar question.
It's recommended to set net.ipv4.ip_local_port_range = 1024 65535 in sysctl.conf.
However, for a specific web application, nginx is programmed to listen at port 80 and 443 (for example). Then in such a scenario, why does setting the port range between 1024 to 65535 matter?
Comment: Take a look https://en.wikipedia.org/wiki/Ephemeral_port
Answer: The net.ipv4.ip_local_port_range value is used to set the port range for outgoing connections. You generally only have to make changes to this on busy systems. Port 80 and port 443 are where webservers generally listen.


Comparar dados de duas tabelas SQL Server

Question: Boa noite,
Estou estudando consultas SQL e me deparei com um problema em uma consulta, tenho duas tabelas:
Tabela: Produtos
<code>+----------------+--------------+--------+
| Codigo         | Produto      | Valor  |
+----------------+--------------+--------+
| 01             | Pipoca       | 5.00   |
| 02             | Refrigerante | 4.50   |
| 03             | Chocolate    | 6.00   |
| 04             | Amendoas     | 18.90  |
| 05             | Macarrão     | 3.69   |
+----------------+--------------+--------+
</code>
Tabela: Pedidos
<code>+----------------+--------------+--------+
| Codigo         | Produto      | Valor  |
+----------------+--------------+--------+
| 01             | Pipoca       | 2.90   |
| 02             | Refrigerante | 4.70   |
| 03             | Chocolate    | 5.80   |
| 04             | Amendoas     | 17.90  |
| 05             | Macarrão     | 4.05   |
| 06             | Batata       | 7.00   |
+----------------+--------------+--------+
</code>
Preciso fazer uma consulta que me retorne a seguinte tabela:
<code>+----------------+--------------+------------+
| Codigo         | Produto      | Diferenca  |
+----------------+--------------+------------+
| 01             | Pipoca       |  2.10      |
| 02             | Refrigerante | -0.20      |
| 03             | Chocolate    |  0.20      |
| 04             | Amendoas     |  1.00      |
| 05             | Macarrão     |  0.36      |
| 06             | Batata       |  7.00      |
+----------------+--------------+------------+
</code>
Alguem por favor pode me ajudar ?
Answer: Respondendo ao teu cenário podes fazer algo deste tipo
<code>   select
    ISNULL(A.codigo,B.codigo),
    ISNULL(A.produto, B.produto),
    (ISNULL(B.valor,0) - ISNULL(A.valor,0)) as Valor
from produtos A  with (nolock) right join pedidos B with (nolock)
ON A.codigo=B.codigo
</code>
Adicionei também o parametro WITH (NOLOCK) que deves pensar em usar. O comando SELECT permite o uso desta opção NOLOCK, evitando assim os bloqueios com os comandos de INSERT.


normal distribution is essential in t test to compare two independent samples?

Question: In student t test to compare the means of two samples, whether the normal distribution of each sample is prehypothesis or not?
As we know, t test is used for comparing two independent small samples with the size of less than 30 (in each sample). In small sample usually the statistically distribution of sample is not normal. If normality distribution is prehypothesis in t test, we have to transforme (such as square root) data before t test.
Comment: Does this answer your question? [Normality of dependent variable = normality of residuals?](https://stats.stackexchange.com/questions/60410/normality-of-dependent-variable-normality-of-residuals)
Comment: The distribution underlying a sample has *nothing* to do with the sample size.  Do not confuse the distribution of a sample--its *empirical* distribution--with the distribution you use to model it!  (*No* empirical distribution is Normal.)
Answer: No you don't need to transform before the test.  Research has shown that the t-test is quite reliable from departures of normality.  In addition, it's appropriate for small sample sizes of e.g. 4, 6, 8, etc. The only thing you wouldn't want is a strong outlier(s), since averages and s.d. are used.  For example, the average of the four numbers 1,2,3, and 1000000 is a little above 250000 = 1000006/4.  So on the number line, the average of 250000 lies somewhere in outer space a 1/4 of the distance to 1000000, where there happens to be no data.
The non-parametric Mann-Whitney or Wilcoxon rank sum test can guard against outlier effects as they are rank-based.  The general idea is that if an outlier is present and ranks are used, the average of the ranks 1,2,3,4 for the four values 1,2,3,1000000 is 2.5=10/4 -- which is not precisely what Mann-Whitney does, but is similar with evaluations for ties.  The alternative hypothesis for Mann-Whitney is also that the two samples came from different distributions.  But you still need some sort of central tendency for non-parametric tests.
For the t-test, you also have to know if the s.d. are equal between the two samples.  If not, you can make an adjustment to the d.f. ($\nu=n_1 + n_2-2$), or use a Welch test.
Another important point is that parametric and non-parametric 2-sample tests for equality of means are for unimodal distributions of data, not multimodal with several large humps or spikes in distributions.
Mann-Whitney is also not exactly the same as Wilcoxon rank sum, since there is a slight variation in the numerator of their test statistics.
If you look at tail probabilities for the $t$-distribution (range of $\nu$) and standard normal, you'll see that the standard normal pretty much starts to approximate $t$ near samples sizes of $n \sim 120$.  So I would use a Z-test for samples sizes above $n=120$, and call it a large sample test, and simply say the $t$ is for small samples.
Computationally, I like to use Z tests for large samples, since computing tail probabilities for the t-distribution is very expensive when compared with Z-scores tail probabilities.


Is this function $y=-\ln\left(1+\frac{\sin x -\cos x}{2}\right)$ convex?

Question: Is this function convex for $x\in[0,\frac{\pi}{4}]$?
$$y=-\ln\left(1+\frac{\sin x -\cos x}{2}\right)$$
without use the derivative.
Answer: Disclaimer: it is quite a long exercise in trigonometry to avoid the use of derivatives to prove the convexity.
Since the function is continuous, you only need the midpoint-convexity in order to prove the convexity. If we take $[x,y]\subset[0,\pi/4]$, we need to prove:
$$-2\log\left(1+\frac{1}{\sqrt{2}}\sin\left(\frac{x+y}{2}-\frac{\pi}{4}\right)\right)\leq -\log\left(1+\frac{1}{\sqrt{2}}\sin\left(x-\frac{\pi}{4}\right)\right)-\log\left(1+\frac{1}{\sqrt{2}}\sin\left(y-\frac{\pi}{4}\right)\right)$$
that equivalent to:
$$\left(1+\frac{1}{\sqrt{2}}\sin\left(\frac{x+y}{2}-\frac{\pi}{4}\right)\right)^2 \geq \left(1+\frac{1}{\sqrt{2}}\sin\left(x-\frac{\pi}{4}\right)\right)\cdot\left(1+\frac{1}{\sqrt{2}}\sin\left(y-\frac{\pi}{4}\right)\right)$$
or to:
$$\left(1-\frac{1}{\sqrt{2}}\sin\left(\frac{z+w}{2}\right)\right)^2 \geq \left(1-\frac{1}{\sqrt{2}}\sin z\right)\cdot\left(1-\frac{1}{\sqrt{2}}\sin w\right)$$
for $[z=\pi/4-y,w=\pi/4-x]\subset[0,\pi/4]$. If we continue expanding we get:
$$-\frac{2}{\sqrt{2}}\sin\left(\frac{z+w}{2}\right)+\frac{1}{2}\sin^2\left(\frac{z+w}{2}\right) \geq -\frac{2}{\sqrt{2}}\frac{\sin z+\sin w}{2}+\frac{1}{2}\sin w \sin z$$
or:
$$\sqrt{2}\sin\left(\frac{z+w}{2}\right)\left(1-\cos\left(\frac{z-w}{2}\right)\right) \leq \frac{1}{2}\left(\frac{1-\cos(z+w)}{2}-\sin w \sin z\right),$$
$$2\sqrt{2}\sin\left(\frac{z+w}{2}\right)\left(1-\cos\left(\frac{z-w}{2}\right)\right) \leq \sin^2\frac{z-w}{2},$$
$$\sqrt{2}\sin\left(\frac{w+z}{2}\right) \leq \cos^2\frac{w-z}{4},$$
but if $w-z=u\in[0,\pi/4]$, then $\frac{w+z}{2}\leq \frac{\pi}{4}-\frac{u}{2}$, hence the LHS is $\leq \sqrt{2}\sin(\pi/4-u/2)$, so we just need to prove that for any $u\in[0,\pi/4]$ we have:
$$ \sqrt{2}\sin\left(\frac{\pi}{4}-\frac{u}{2}\right)\leq \cos^2\left(\frac{u}{2}\right),$$
or:
$$ \cos\frac{u}{2}-\sin\frac{u}{2}\leq \cos^2\left(\frac{u}{2}\right),$$
$$ \sin(u/2) \geq \cos(u/2)-\cos^2(u/2),$$
$$ \cot(u/4) \geq \cos(u/2), $$
That is trivial since over $[0,\pi/4]$ the LHS is greater than $\cot\frac{\pi}{16}>1$ while the RHS is obviously $\leq 1$.
Answer:
Look at the picture, do you think it is convex or concave?
Comment: A picture is not a proof.


Only the empty set is equal to the interior of its boundary.

Question: Let $(X,d)$ be an arbitrary metric space, with $X$ being the set, and $d$ the metric. Let $S$ be a subset of $X$. Let $bd(S)$ be the boundary of $S$, in metric space $(X,d)$.
I want to show that if the interior of $bd(S)$ is equal to $S$, then $S$ is the empty set.
I encountered this question as part of Exercise C.9 in Efe Ok's "Real Analysis with Economic Applications," which I am reading for self-study and review, so this is not for an assignment. The exercise has several other parts, but I figured out those, unlike this one.
What I have so far hasn't helped me much. My plan was to assume that $x$ is an arbitrary element in the interior of $bd(S)$, and then derive that $x$ cannot exist. The "assume" part of that plan was fine, but the "derive" not so much. Can anyone who finds this question easy give me a little push to get me going? I'd love a hint even better than a full solution.
Comment: A hint here: https://math.stackexchange.com/questions/1142892/prove-that-the-interior-of-the-boundary-is-empty
Answer: Suppose otherwise. Then there is some $x\in S$. Therefore, $x$ belongs to the interior of $\operatorname{bd}S$. In other words, there is some $r>0$ such that $B(x,r)\subset\operatorname{bd}S$. Since $B(x,r)$ is an open set, it is therefore a subset of the interior of $\operatorname{bd}S$, that is, it is a subset of $S$. But then $B(x,r)\subset\mathring S$. In particular, $x\in\mathring S$. This is impossible, because $x\in\operatorname{bd}S=\overline S\setminus\mathring S$.
Comment: I had gone as far as B(x,r) is a subset of the interior of bd(S). But then... why can we infer that it follows that B(x,r) is a subset of S? That's the step I got stuck at: if B(x,r) is contained in S, then sure, x is an interior point and we are done. But the interior of bd(S) need not be contained in S, need it?
Comment: @JonE. Since $B(x,r)$ is a subset of the interior of $\operatorname{bd}S$ and since the interior of $\operatorname{bd}S$  is equal to $S$, $B(x,r)$ is a subset of $S$.
Comment: Crystal clear now. I had lost track of the starting point that S is equal to the interior of its boundary. This problem was not as hard as I made it to be. My first time in mathstackexchange. This is amazing.


Interpreting a Tukey - Kramer Confidence Interval Plot

Question: In order to see if any statistically significant differences in the means of 4 particular diets exist, a post-hoc test is conducted i.e. Tukey – Kramer.
Could someone please explain to me the plot which is attached below?
Note: Tukey - Kramer is being used here as there is not equal observations between diets.
Comment: What don't you understand?
Comment: The plot in general. I'm unsure about how to interpret it.
Answer: There are 4 diets - which gives 6 possible pairwise comparisons between them: 1-2, 1-3, 1-4, 2-3, 2-4, and 3-4 (2-1 would be the same as 1-2, so we don't count it twice).
The plot has all these comparisons displayed at different heights with the label on the left y axis side.
The x-axis represent the mean differences that were found between those pairs. So for example the comparison 2-1 had a mean difference of 20.
The extended lines show the 95% confidence intervals. In this case if the confidence interval crosses the 0 point - the difference would not be statistically significant. In the plot colors seem to indicate this significance: red lines do not cross the 0 so the differences in their means were found to be statistically significant.
Based on this we could reason that diet No. 1 was different from the rest as all the pairwise comparisons that included diet 1 were statistically significant (red in the plot) while all the other comparisons were not.
Answer: On the y-axis you have all the tested contrasts, that is 2 vs 1, 3 vs 1, ... 4 vs 2. On the x-axis you have the mean differences (the points) for that particular contrast. The lines represent the 95 % confidence interval.
So for ex. the contrast on the bottom, 2 vs 1, says that there is a mean difference of 20 between 2 and 1, and the 95 % CI is in the range of 0 to 40.


infinitely many Abelian extensions of $K$ whose Galois group is $G$.

Question: Let $K$ be a finite extension of $\mathbb{Q}$ and $G$ be a finite Abelian group. Show that there exist infinitely many Abelian extensions of $K$ whose Galois group is $G$.
This a exercise from Lang and I'm stuck on it without any idea, can one please help ?
Answer: We can write $G= \prod_{i=1}^{k} Z_{n_i}$. Now using the fact that there are infinitely many primes $p$ of form $(n_i-1)|p$ for all $i$, we get infinitely many tuples of primes $S_j=(p_{j,1},p_{j,2},..,p_{j,k})$ such that $n_i-1|(p_{j,i}-1)$ for all $1\leq i\leq k$. Now we can make a infinite set $I$ such that for every distinct pair $i,j\in I$ we've $S_i\cap S_j=\mathbb{Q}$. Now, there is $E_j \subset \mathbb{Q}(\omega_{\prod p_{j,i}})$ such that $Gal(E_{j}/\mathbb{Q})=G$.
To do this you need to use the Galois correspondence and the fact that $Gal(\mathbb{Q}(w_n)/Q)$ is Abelian for all $n$ so, any intermediate extension is normal and hence Galois over $Q$. Now note that $E_i \cap E_j=\mathbb{Q}$ for any distinct $i,j \in I$.
Now $Gal(KE_i/K)=Gal(E_i/K\cap E_i)$ for all $i\in I$. Now since $Q \subset E_i \cap K \subset K$ and $[K:Q] <\infty$ so exist a infinite subset $I'$ of $I$ such that $E_i\cap K=E_j\cap K$ for any $i,j \in I'$. Bug then $E_i\cap K= (E_i\cap K)\cap (E_j\cap K)=K\cap (E_i\cap E_j)=K \cap \mathbb{Q}=\mathbb{Q}$ for any $i\neq j \in I'$.
So, then for any $i\in I'$ we've $Gal(KE_i/K)=Gal(E_i/\mathbb{Q})=G$. Now as $KE_{i}\cap KE_j=K$ and $I'$ is infinite so we're done.


Visual C++: Good way to draw and animated fill path to screen?

Question: I want to use Visual C++ to animate fill paths to screen. I have done it with C# before, but now switch to C++ for better perfomance and want do more complex works in the future.
Here is the concept in C#:
In a Canvas I have a number of Path. These paths are closed geometries combine of LineTo and QuadraticBezierTo functions.

Firstly, I fill Silver color for all path.
Then for each path, I fill Green color from one end to other end (up/down/left/right direction) (imagine a progress bar increase its value from min to max). I do it by set the Fill brush of the path to a LinearGradientBrush with two color Green and Silver with same offset, then increase the offset from 0 to 1 by Timer.
When a path is fully green, continue with next path.
When all path is fill with Green, come back first step.

I want to do same thing in Visual C++. I need to know an effective way to:

Create and store paths in a collection to reuse. Because the path is quite lot of point, recreate them repeatly take lots of CPU usage.
Draw all paths to a window.
Do animation fill like step 2, 3, 4 in above concept.

So, what I need is:

A suitable way to create and store closed paths. Note: paths are combine of points connect by functions same with C# LineTo and QuadraticBezierTo function.
Draw and animated fill the paths to screen.

Can you please suggest one way to do above step? (outline what I have to read, then I can study about it myself). I know basic of Visual C++, Win32 GUI and a little about draw context (HDC) and GDI, but only start to learn Graphic/Drawing.
Sorry about my English! If anythings I explain dont clear, please let me know.
Comment: So, essentially, you are trying to prematurely optimize code you haven't even written yet? Why not write the code, profile it, and then come back when profiling has identified any bottlenecks?
Comment: @IInspectable I already written it nearly an year ago, and it work. I also spent a lot of time optimize it (the CPU usage is 8 - 10%)  But the main of it is functions I list above. And it is about serveral page of code. I think if I post full of the code here it look like I'm asking people convert my code for me, so I don't. If you want to see, I can post it. I want do it by native C++, one reason is I want to learn graphics drawing, wich I know I can do much more complex work compare to C#
Answer: how many is quite lot of point ? what is the target framerate? for low enough counts you can use GDI for this otherwise you need HW acceleration like OpenGL,DirectX.
I assume 2D so You need:

store your path as list of segments
for example like this:
struct path_segment
 {
 int p0[2],p1[2],p2[2]; // points
 int type; // line/bezier
 float length; // length in pixels or whatever
 };
const int MAX=1024;     // max number of segments
path_segment path[MAX]; // list of segments can use any template like List<path_segment> path; instead
int paths=0; // actual number of segments;
float length=0.0; // while path length in pixels or whatever

write functions to load and render path[]
The render is just for visual check if you load is OK ... for now atlest
rewrite the render so
it take float t=<0,1> as input parameter which will render path below t with one color and the rest with other. something like this:
int i;
float l=0.0,q,l0=t*length; // separation length;
for (i=0;i<paths;i++)
 {
 q=l+path[i].length;
 if (q>=l0)
  {
  // split/render path[i] to  <   0,l-l0> with color1
  // split/render path[i] to  <l-l0,q-l0> with color2
  // if you need split parameter in <0,1> then =(l-l0)/path[i].length;
  i++; break;
  }
 else
  {
  //render path[i] with color1
  }
 l=q;
 }
for (;i<paths;i++)
 {
 //render path[i] with color2
 }

use backbuffer for speedup
so render whole path with color1 to some bitmap. On each animation step just render the newly added color1 stuff. And on each redraw just copy the bitmap to screen instead of rendering the same geometry over and over. Of coarse if you have zoom/pan/resize capabilities you need to redraw the bitmap fully on each of those changes ...
Comment: @Sakura you do not need to mask anything in back buffer. At first render it with silver (the whole path) and on each timer render the green path that has been added as already traveled (not the whole thing just the incremental step) that should be fast enough ... you do not need the `BitBlt` ... you can render lines and bezier directly with GDI no need for pixel access
Comment: The backbuffer is good idea! Never think of that. Assume I render the path to bitmap, for example with **Silver color**, First step I draw all bitmap to screen, after that I draw parts of each bitmap by timer, so I have to deal with the **overlap** of bitmaps *(each path can overlap eachother, but I must not draw the white rectangle a round the path of the bitmap to screen)* and draw these parts with **Green color**. For draw bitmap I know `BitBlt` but don't know how to avoid draw the white color to screen, and how to draw Silver color bitmap to Green color.Could you point me 2 these function?
Comment: And for more info, the frame rate is one draw/10 miliseconds, the size of whole draw area is 160x160px, with have 20 - 80 paths, each path contains 30 - 50 points, Total duration from 1 second to 1 minute
Comment: Yes, that is good point. What I consider is the first step, when I have to render all (for example 80) paths to screen at one time *(something like placeholder, indicate user that each path will be draw at which position, imagine a book for kid pratice writing, each character will have a dim shap for kid to follow)*. Ah, I just think maybe this first step I render it to bimap alone, then when finish a circle I draw it to screen. Now the problem solved, many thanks for your help :)


SCP with password authentication only doesn't ask me for password

Question: I'm trying to copy files from one server to another with scp.
On both servers, I configured ssh port to 222. sshd_config for both servers is exactly the same (no RootLogin, PasswordAuthentication enabled)
For many reasons too long to explain here, I can't use key authentication.
When I use scp to copy from server A to server B (logged to A), it works. But it doesn't work when I'm doing the same thing from B to A (logged to B) : I get an error message "permission denied" and scp doesn't ask me for password (although the password authentication is enabled)
Here is the command I use (logged on server B) :
scp -P 222 -vvv ~/backup/file user@serverA:/home/user/backup

And here are the last lines of the output :
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: password
debug3: start over, passed a different list password
debug3: preferred publickey,keyboard-interactive
debug1: No more authentication methods to try.
user@serverA: Permission denied (password).

Why doesn't scp ask me for password, whereas "password" is enabled (as it is written in the 2nd "debug1" line) ?
Thank you.
Comment: You sure that PW auth for `user` is enabled? If I try this with PW and `-vvv` I get this output: `debug3: send packet: type 50` `debug2: we sent a password packet, wait for reply`
`debug3: receive packet: type 51`
Answer: The best solution would be to ask the person who disabled publickey authentication on that server why and then go fix that. Using publickey authentication is more convenient and more secure than passwords.
The reason authentication fails for you is that no authentication method is enabled on both client and server. The authentication methods enabled on the server are:
debug1: Authentications that can continue: password

And the authentication methods enabled on the client are:
debug3: preferred publickey,keyboard-interactive

You can pass -o PreferredAuthentications=password to scp to only use password authentication.
Comment: You're my man! "UsePasswordAuthentication" was set to "No" in ssh_config on server B. Corrected it to "yes", and  it's ok. Thanks a lot.


Creating, modifying and removing folders and folder structures in Drupal 7

Question: I know that it is possible to delete files from the File Browser view, but is there a way to create, modify and remove folders in Drupal 7?
Answer: If you're using 'file browser' than you probably have the IMCE file manager enabled. What you want to do then is enable the extension module IMCE_mkdir to create directories and subdirectories (within folders your web user has permission to access):

IMCE Mkdir allows users to create and delete sub-directories under
  directories assigned by IMCE.
Answer: Another relevant module, IMCE Tools:
https://www.drupal.org/project/imce_tools


IntelliJ mxml giving error about id attribute used as id in typed class

Question: I have a typed class in actionscript:
public class Cat {
    public var id:int;
    public var name:String;
}

I am using an instance variable in an mxml component:
<valueobjects:Cat id="selected_cat"/>

In IntelliJ the id for cat is coming up as an error, "invalid integer value", although it will compile without error.  This error appears in the IDE when editing the file and lists it as an error at bottom.  Does anyone know of any tricks to tell IntelliJ about this class or the property.  Or are there any metadata tags to identify the attribute so the mxml parser will be happy?
Thanks in advanced.
Answer: Yes, the problem is, that usually id is a String used in markup to set an id of type String. Flex supports that via UIComponent or IMXMLObject. You should not use ValueObjects in the markup, unless the class implements IMXMLObject.
Answer: To declare a non-visual object in markup you have to use the fx:declarations tag in Flex 4 and above.
The id property in each mxml tag (whether visual or not) acts as a way to reference this object from the rest of the code.
In other words, its the markup equivalent of this.
var selected_car:Car
So the id has to be a String property always.
In your class you declare the id as an int property which is confusing for the compiler because it doesn't know which one is valid.
If you need to work with your class without changing it, you'll have to create instances using AS and not MXML. If you need to work with mxml (to have binding enabled etc) you'll need to change the property name to something like catID perhaps.


hook_theme() in a custom file of my module

Question: I'm facing an issue for a few hours now. I created a new module that must render an admin page with some settings and another one with analytics data. The second one must use a custom template file that I created for the occasion.
I added a hook_theme() in my .module file and everything worked fine for a while.
When refactoring my code I wanted to move the hook_theme() in a subfile.inc of my module. Even though I cleared the caches, I always get the issue Theme hook "my_custom_template" not found..
After moving back the hook in the .module file everything work again.
Are they some hooks that must be in the .module file only. As the hook_install() and hook_uninstall() must be in the .install file?
Answer: Just to clarify, you mean the actual hook_theme() implementation, correct? Not a theme hook you are defining in hook_theme(). If so, by default, all hooks must be in the .module file. Hooks are meant to be callable at any time, and only .module files are loaded by default on every page load. However you can tell Drupal that a hook is in a different file by implementing hook_hook_info():
function hook_hook_info()
{
   $hooks['theme'] = ['group' => 'theme'];

   return $hooks;
}

With this code, Drupal will look for the hook (the array key 'theme') in the file MODULENAME.GROUPNAME.inc. In this case your GROUPNAME is defined as 'theme' in hook_hook_info(), so Drupal will load MODULENAME.theme.inc, whenever hook_theme() is invoked.
Now, if you meant that you want to put a theme hook that you define inside hook_theme() in another file, then you need to declare the file for that theme hook:
function hook_theme()
{
  return array
  (
    'some_theme_key' => array
    (
      'variables' => array(),
      'file' => 'path/to/file.inc', // relative to module root
    ),
  );
}

In this case, when the system tries to load the theme some_theme_key, it will load the file [MODULEFOLDER]/path/to/file.inc.
Comment: Thanks Jaypan, I wasn't aware that all hooks must be in the .module file. I thought that my .inc file mentioned in the .info file would be loaded as well.
Comment: I think those files are only scanned for classes. I'm not entirely clear on that though. It was something that was initially introduced as a requirement for D7, but then that requirement was dropped before D7 was released. The functionality was retained, but it was never clear to me exactly what/how it worked.
Comment: Ok, thanks for the addition. Would a ```require_once``` at the begining of the *.module* file be considered wrong?
Comment: Nothing is wrong - if it works it works. But the method I showed will be more lightweight.
Answer: Try using module_load_include() in your custom_module.module to load your .inc file
Comment: You should use `require_once` instead, `module_load_include` is only for use inside functions when Drupal is bootstrapped
Comment: Totally right Clive . Jaypan answer is the normal way. It must be a cache matter, but Tim, you can try first if it works with module_load_include, if so, switch to Clive answer's for Best practices.
Answer: Try adding the reference to your file subfile.inc into info-file of your module.
files[] = subfile.inc

Comment: `files` is for class autoloading, this won't have the desired effect


TypeError: no implicit conversion of Symbol into Integer while reading YAML in Ruby

Question: I have the following defined in a module in my Rails application:
module Selecting
  module Execution
    class ExecuteSpecific

      def self.perform!
        input = Data::FetchData.new.perform_action(param1, params2)

To make the code more general I want to remove the specific methodcall from the function and mode it to a YAML file as such:
:Newname:
  - example: 'Data::FetchData.new.perform_action(param1, params2)'

and refactor the above to ("name" should be passed as a symbol):
module Selecting
  module Execution
    class ExecuteSpecific

      def self.perform! name

        new = YAML.load_file('path/to/file.yml')[name]
        input = new[:example]

This return a

TypeError: no implicit conversion of Symbol into Integer

How can that be fixed?
Answer: That error is saying you are using a symbol where it expects an integer.  The only place you are doing that is where you call new[:example].  Yaml.load_file returns array of strings and not symbols, so if you access your yaml loaded document using string index instead of symbol that should solve the problem.
Eg. input = new['example']
Comment: Thank you for the quick reply. But if it returns 'Data::FetchData.new.perform_action(param1, params2)' as a string it's not going to be executed?


Can't restore files structure with git reset

Question: I changed file directories structure in my project and now when I do git reset --hard 514c98bd I do get my files as they were at 514c98bd commit, but not the directories structure.
I changed directories structure via IDE and now it's completely a mess, it's impossible to get everything as before by hands. Why git doesn't restore files as they were in directories and if it does - how can I do it? Thanks a lot.
Answer: My guess is that you have extra files present?  If so, try "git clean -dfx" to do a hard clean (including directories, force removal, remove .gitignored files).  Also: please be more specific about your problem.  "but not the directories structure" tells us that you don't have what you expect; it does not tell us what you have or what you expected.


Elementary Number Theory and Congruences

Question: Let $f(x) = x^m + a_1x^{m−1} + · · · + a_{m−1}x + a_m$, with $a_j \in \mathbb{Z}$, be a polynomial with integer coefficients and $m \geq 1$.
(i) Show that if $a$ and $b$ are integers with $a \equiv b \pmod{n}$, then $f(a) \equiv f(b) \pmod{n}$.
I think I am supposed to use the polynomial division algorithm here?
(ii) Suppose that for some integer $a$, $f(a) = p$ is a prime. Show that, if $f(b) = q$ is also a prime for some integer $b$ with $b \equiv a \pmod{p}$, then $p = q$.
(iii) As in part (ii), suppose that for some integer $a$, $f(a) = p$ is a prime. Show that there must be an integer $b$ with $f(b)$ not a prime. (Hence there are no 'magic' polynomials, giving only prime values. ) Hint: consider the polynomial $f(x) − p$ and use (ii).
Please advise on question above.
Thank you!
Comment: Hi, @user711963! Typically on MSE (Maths Stack Exchange), we try to not just give answers but hints/help. What have you tried for these questions already? How far have you got? E.g. for (i), have you tried special cases, e.g. $f(x)=x^n$?
Comment: I am a little confused. If m=1, is it $x+a_1$ or $x+a_0 x +a_1$
Answer: i) If you can prove $a\equiv b$ and $j \equiv k$ that $aj \equiv bk$ and $a+j \equiv b+k$ you are done.
By induction you can prove that if $a_i \equiv b_i$, and $a_1 + .... + a_m \equiv b_1 + .... + b_m$ then $(a_1+ ......+a_m) + a_{m+1} \equiv (b_1 + .... + b_m) + b_{m+1}$ so the result holds for all sums no matter how many sumands.
Similarly for products no matter how many multicands.
And if true for products then true for powers which are just products where all multicands are equal.
And if true for products then true for polynomials which are a sum of products of coefficients and powers.
ii) apply i)
If $a \equiv b \pmod p$ then $0\equiv p = f(a)\equiv f(b) =q\pmod p$.  So $q \equiv 0 \pmod p$ so $p|q$.  But $q$ is prime.  So $p=q$.
iii) Not sure I'm getting their hint.
Suppose $f(n)$ is prime for all integers $n$.
But one of the following must be true:
1) $f(n)$ is never prime for any integer $n$.
If so we have nothing to prove.
2) The is exactly one prime $p$ that $f(n)$ is ever equal to.
As $n\to \infty$ we have $f(n)\to \infty$ so $f$ has more than value.  So some values are not $p$ and as $p$ was the only prime some values are not prime.
3) There is an $a$ and $b$ so that $f(a)=p$ a prime and $f(b)=q$ a prime not equal to $p$ then by Bizout's Theory there are $Mp + Nq = a-b$ so $b +Nq = a-Mp$.  Let $k=b+Nq=a-Mp$
So by ii) if $f(k)$ is prime then $f(b+Nq) =q$ but if $f(k)$ is prime then $f(a-Mp)=p$ so that's a contradiction.
So $f(k)$ is not prime.
So there will always be a value, $k$ where $f(k)$ is not prime.


What is the index of a subgroup $H$ in a group $G$?

Question: I have read multiple definitions so far but something is not clicking.
My most naive understanding is that $|G:H|$ is a "number" (could be infinite) that represents how many times $H$ is in $G$.
But even this doesn't seem fully correct.
I would like a general non-formal explanation and perhaps an example to understand the intuition.
Comment: I would word it slightly differently. $|G:H|$ is the number of (left or right) cosets of $H$. A coset is not a copy of $H$; more correctly one might call it a *translate* of $H$. Distinct cosets are disjoint. So one might say that the cosets of $H$ constitute a "tiling" of $G$, and $|G:H|$ is the number of tiles.
Comment: An example: take a plane in 3D space (a group under vector addition). Then, all the planes that are parallel to this plane are its cosets; you can obtain them by translating the planes by a vector not in the plane. Since 3D space is made up of infinitely many such parallel planes, the index is infinite.
Comment: Your understanding seems about right.
Comment: @bungo Your comment has one major flaw which is: you made it a comment and not a solution! It would be a great solution, I think.
Answer: Upgrading my comment to an answer:
You have the right intuition, but I would word it slightly differently.
$|G:H|$ is the number of (left or right) cosets of $H$. A coset is not a copy of $H$; indeed, a coset of $H$ isn't even a subgroup unless it's $H$ itself.
It would be more correct to call the coset $aH$ a translate of $H$ by the element $a$. Distinct cosets are disjoint and form a partition of $G$. So one might say that the cosets of $H$ constitute a "tiling" of $G$, and $|G:H|$ is the number of tiles.
To take a concrete example, let $G$ be the additive group of integers modulo $12$, and let $H$ be the subgroup generated by $4$, so $H = \{0, 4, 8\}$. Then there are four distinct cosets of $H$, namely:
$$\begin{aligned}
H &= \{0, 4, 8\} \\
1+H &= \{1, 5, 9\} \\
2+H &= \{2, 6, 10\} \\
3+H &= \{3, 7, 11\} \\
\end{aligned}$$
In other words, the cosets are $H$ and its translates $1+H$, $2+H$, and $3+H$.
Together these four cosets contain all the elements of $G$, so they constitute a partition (tiling) of $G$. The number of tiles is the number of cosets, which is $|G:H| = |G|/|H| = 12/3 = 4$.
Comment: Beautiful answer to "What is the index ..." without using the word index even once. ;-)
Answer: Your naive understanding is roughly correct, especially for the finite groups.
Here are two examples in the infinite case in the same setup (you should draw pictures while reading this).
The set of all nonzero complex numbers, is a group under multiplication of complex numbers, call it $G$. This can be pictured as the plane with a hole at the origin.  Let $H$ be the subset there consisting of number of modulus 1 (unit circle). One checks easily that $H$ is a subgroup.
It is clear to visualize that all concentric circles centred at the  origin one each for every positive number as the radius, cover the whole of  $G$.
Any particular circle of radius $R$, each point there is obtained by multiplying elements of $H$ (the unit circle) by $R$.
 Each of this circle is a coset and they are all disjoint, with the whole group as their union. The index here is number of possible values for $R$ (which is the set of positive real numbers), the number of cosets.
Now coming the other way around, now take $K$ to be the set of positive real numbers as a subset of $G$. This $K$ is also a subgroup of $G$, geometrically this is a ray.
Now rotate this ray by various angles around the origin. For each angle you get a different ray, always starting from the origin. These rays also cover up the group $G$, and they are disjoint. One each for every possible angle in the  semi-closed interval $[0, 2\pi)$.
Each such ray is obtained by multiplying every number in $H$ by the fixed complex number $e^{i\theta}$, so they are all cosets of $K$.
To summarise: in the first case the circle is a subgroup  and the index is infinite with one coset corresponding to every possible positive number as radius.
In the second case positive real numbers form a subgroup with index again infinite, corresponding to every possible angle.
NOTE: When you study the concept quotient groups the above example is worth revisiting and one can see that this says $G/H$ is $K$ and $G/K$ is $H$, or that $G$ is the direct product of $H$ and $K$. (Here we are working with abelian groups and  hence normality is automatic for all subgroups).