Do we need CSRF verification for every POST request?

Question: I am just building a simple HTML form with POST method and unfortunately I am finding CSRF verification error.
This is just a simple html form using POST method on localhost. There are no cross sites involved. I could definitely fix it by using csrf_token but I still don't understand why django is asking me for that..
There are no re-directions/ iframes involved here...
So, why this is happening?? is this normal to all ??
# Also tried using RequestContext(request) but there isn't any change in the error

#settings.py
'django.middleware.csrf.CsrfViewMiddleware' in MIDDLEWARE_CLASSES

#views.py

# url for home page is "" i.e, http://127.0.0.1:8000/
def HomePage (request):
    if request.method == "POST":
        form = myForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            context = { "myForm" : myForm(choices),
                        "values" : data,
                       }
            return render_to_response("home.html", context)
    else:
        form = myForm(choices)
    context = {"myForm" : form}
    return render_to_response("home.html", context)

# home.html

            <form action="" method="post">

                    {{myForm.as_table}}

                <input name="enter" type="submit" value="enter"/>
            </form>
            {{values}}

# forms.py

class myForm (forms.Form):

    def __init__(self, my_choices,*args, **kwargs):
        super(myForm, self).__init__(*args, **kwargs)
        self.fields['Friends'] = forms.ChoiceField(choices=my_choices)

    message = forms.CharField()

Comment: If you have `django.middleware.csrf.CsrfViewMiddleware` in your middleware in `settings.py`, then it will be checked for each `POST` request. You have remove that if you really don't want _CSRF_ feature, but that is not recommended though. Alternatively, use `{% csrf_token %}` in template or `csrf_excempt` for view.
Answer: If you do a post request, you typically change the state of the server. If you change the state of the server, you don't want to allow other sites to do so. To protect against other sites issueing post-requests on your server, you add csrf protection. Therefore the solution should (imho) never be to remove the Csrf protection. Depending on the situation, either of the following two is the case:

Your post request does not change the state. In that case, make it a get request.
Your post request changes the state. You need CSRF.
Comment: This is a good answer but in my opinion misses a key point of CSRF. The malicious website is submitting the POST *using the credentials of a logged-in user* who visits the malicious site.
Answer: The error message you got but didn't show explains exactly what you are doing wrong: you should ensure that

the view function uses RequestContext
      for the template, instead of Context.
Comment: I added `context_instance=RequestContext(request)` but there isn't any change in the error msg


Rank of a random variable that follows a Uniform Distribution (0,1)

Question: Well the question is a little easier .. Let X be a random variable that follows a Uniform distribution (0,1)(Uniform Standard). What is rank of the variable? (Values can take). I have a confusion between whether the variable can take real values between the interval (0,1) or can only take the values 0 or 1
Comment: Can you write the density function for $X$ uniformly distributed over $[0,1]$? Those points with non-zero probability belong to the rank of $X$!
Comment: @Kanna: Be careful that here, **every** point has zero probability... I see what you mean to ask by your second question but it needs to be slightly reformulated.
Comment: @DidierPiau Thank You very much! Sure, I meant "non-zero density"!
Comment: @Kan: Yes. With the further caveat that the density function is only defined almost surely... Hence for every point there exists a density function which is zero at this point... :-)
Answer:
Let X be a random variable that follows a
  Uniform distribution (0,1)(Uniform Standard).

Do you mean a discrete or a continuous distribution?  Do you mean [0,1] or (0,1)?  Or are these your questions?
Comment: Sorry is a continuos distribution. that is X ~ Uniform (0,1). I thought that the random variable that follows a standard uniform distribution is understood to be a continuous distribution (by [definition](http://en.wikipedia.org/wiki/Uniform_distribution_(continuous)))
Comment: Melkhiah: If the definition is well known to you, why do you ask this question?


Do most men even sing that low (A3)?

Question: I just played a tune with the range of A3-D5 (I think that's the correct English terminology). When I started singing I had a problem with the A3.  The last melodic lines is A3-C#4-D4.
This seem lika a popular key (Dm) for this song even though A3 seem low for some men.
I feel a bit embarrased how I can find this difficult.
Do most men even sing this low?  And is this A3 note easy since it is a part of that melosic line?
Comment: A3 is not particularly low at all for a male voice. Are you sure you don't mean A2-D4? (Note that male voices are often written in treble-8vb clef, i.e. the notes are an octave lower than it looks. This _should_ be indicated by a small _8_ below the clef, but that is frequently omitted.)
Comment: A3 is well within the range of pretty much all male and female singers. It is the A right below middle C. I'm wondering if perhaps you were singing an octave lower than what was written?
Comment: I can hit C1 [*just*, only just] & when I was in my 20s could get to G4, though now it's more like C4 :( That was considered to be a better-than-normal range. I think one of us has to be out by an octave in our pitch recognition.
Comment: If not able to provide the score as graphic, then positioning in a note system with clef would help.
Comment: @Tetsujin — perhaps you're both mistaking the octave? C1 is really really really low (in the bass clef, it's under the 5th line below the staff). (I'm not saying you can't be able to hit it, but it is very rare, I would say.) This picture from Wiki could help sorting any mistakes out: https://upload.wikimedia.org/wikipedia/commons/4/41/Scientific_pitch_notation_octaves_of_C.png
Comment: @Ramillies .. Ah, OK - I'm in MIDI. Middle C as C3, note 60, not classical C4. (That's what 10 years of working for Yamaha does to you ;) If we're going by the keyhole in the piano being C4, then I can reach C2 to C5 or so.
Comment: @Tetsujin: That's interesting, I didn't know before that MIDI was adding to the confusion in this way :—).
Answer: A3-D5 is a range accessible to contralto (low female voice) so I'll assume you are talking about A2-D4 instead.  The lowest regular note for baritone (or choir "bass") tends to be about E2.  The lowest regular note for a choir(?) tenor tends to be B2.  Being a "lead quart" below the tonic, touching that note tends to be easier than more extended or elaborate uses of it since it's without accent and the following line and overall harmonic frame is idiomatic enough that not getting the pitch impeccably is less noticeable than with other uses.
Answer: I reckon the range what you're on about- (A3 to D5), would probably be pretty comfortable for most well-trained Tenors, and also, for some exceptionally high Baritones. I'm a higher-end Bari and the range what you're on about's well within my comfortable range- (I wouldn't have much problem with that range at all!) A3's normally about the lowest that I'd be willing to sing- (although, for the record, I can sing all the way down to about E2 on a bloody good day.

Do most men even sing that low (A3)?


Multiple dynamic subdomains and SSL (*.*.mysubdomain.mydomain.com)

Question: I have a requirement to add SSL to a system that uses multiple dynamic subdomains. For example:
Y.X.mysubdomain.mydomain.com
Z.X.mysubdomain.mydomain.com
X = is the name of client and is dynamic
Y & Z = are names of the clients customers and are dynamic
I've looked at wild cards however they only go one level deep (*.mysubdomain.mydomain.com) and I need a way of doing ..mysubdomain.mydomain.com
If there is a way of doing unlimited subdomains of a base domain that would be an option also (..*.mydomain.com)
I've had a look at http://www.digicert.com/unified-communications-ssl-tls.htm however it seems you need to supply them with the subdomains and domains upfront. As these subdomains are dynamic and user generated this is not an option.
Any help or pointers would be most gratefully welcome.
Comment: I think a.b.mydomain.com will match on *.myadmain.com. At least in DNS. Not sure
Answer: You just need a wildcard certificate for *.mydomain.com - this should be enough. Take a look at this option - http://www.digicert.com/welcome/wildcard-plus.htm for instance.
Comment: @LogicWreck A wildcard can't apply to more than one level of subdomain.
Comment: Thanks for this, however from what I can tell I would need to add the subdomains to the Subject Alternative Names list and with them being dynamiclly created and removed I still don't see this working.
Comment: also add the certificate, key and if needed ca certificate for each such subdomain created in their respective configuration in such case. That should do the workaround.


How to check inside the Worker thread if the Main UI Thread is sleeping or not active

Question: I have created a Visual Studio 2019 app, with OutputPanes, one is used for viewing Traces Logs from the WorkerThread.
In the WorkerThread, I fill a CStringList mStrDebugList if somewhat useful has happened, and inform the Main UI with PostMessage to read & show now.
//////////////////////////////////////////////////////////////////////////
//  TRACE Debug messsages for this App wide
void TRACE_DEBUG(LPCTSTR pszstring)
{
    TRACE(pszstring);

    CTestApp* pApp = (CTestApp*)AfxGetApp();
    if (pApp)
    {
        TAutoLock lock(res);
        theApp.mStrDebugList.AddTail(pszstring);
    }

This works, but if the App is minimized or not in the foreground, after hours the CStringList contains too many elements (> 20k) and the Main UI is unresponsive (~5Min) until all elements are read & removed in the UI.
void COutputWnd::FillInfoWindow()
{
    TestApp* pApp = (CTestApp*)AfxGetApp();
    if (pApp)
    {
        TAutoLock lock(res);

        CString str;
        while (!theApp.mStrDebugList.IsEmpty ())
        {
            str.Format(_T("%5d %s"),nCounter, theApp.mStrDebugList.GetHead ());
            m_wndOutputDebug.AddString (str);
            theApp.mStrDebugList.RemoveHead ();
        }

        // Scroll to the end of Listbox
        int nCount = m_wndOutputDebug.GetCount();
        m_wndOutputDebug.SetTopIndex(nCount-1);
    }
}

My question is, how can I check inside the WorkerThread if the UI is not active (dormant), to prevent filling the CStringList with too many elements?
Comment: Message loops and UIs don't stop working just because the window is hidden/minimized. You say you are using `PostMessage()`, but there is no such call in the code you have shown. The real problem is that whatever you are using to trigger `FillInfoWindow()` is not working properly. Fix that instead.
Comment: You mentioned the word "sleep".  Are you actually calling `sleep()` from the UI thread?  The actual UI thread should remain responsive to messages and should not be put to sleep.  EDIT TAutoLock should be OK, if this is what you meant by "sleep", as long as you don't lock the resource except for single log entries.
Comment: Thanks for the state UI don't stop working, if the window is hidden/minimized. That is true, I wasn't sure anymore. I have myself deferred posting the real message to Update the OutputWnd in OnPaint `AfxGetMainWnd()->SendMessageToDescendants(WM_COMMAND, AFX_IDS_IDLEMESSAGE); // update Output Wnd `. That would explain this issue.
Answer: I think your approach is wrong. What will you be doing if the UI (main) thread is "dormant"? Prevent the worker thread from working, ie suspend it? Will it no longer be collecting data? And what will happen when the UI is brought to the foreground again? The worker thread will have to collect ALL the data, which will still need to be added to the debug window, all at once, so the total response time will be yet longer.
If it's adding the data to the debug window (I guess a listbox-derived class) that takes so long, there is no real solution, they need to be added anyway. Only some optimizations:

Call m_wndOutputDebug.SetRedraw(FALSE); before adding the strings and m_wndOutputDebug.SetRedraw(TRUE); and m_wndOutputDebug.Invalidate(); when you are done, maybe the delay is caused by the UI attempting to draw the debug window immediately after each item is added.
Avoid those GetHead()/RemoveHead() calls for browsing the list (it's overhead, as it may rearrange/realloc the list), instead call RemoveAll() when you are done, there is no problem with this because you lock the operation.

A side note (not performance-related), why do you need to call AfxGetApp()? You are not doing anything with it (pApp) anyway. And you have the theApp singleton available (AfxGetApp() should just return the address of theApp, no?).
Comment: Yes, I was also trying to solve flickering issues in the OutputWindow the very wrong way, by slowing down the WorkerThread. Thanks for the optimizations tips. Especially I wasn't aware that AfxGetApp ist consuming many CPU cycles. I have measured that on my machine ~300us vs ~40us.


Euclidean Geometry challenge.

Question:
Can someone help me on this one?
I have found that $\frac{1}{(x+1)^2}+1=\frac{1}{x^2}$, but I can't solve the fourth degree equation that comes with it. There must be a easier way!
Comment: You probably mean a fourth degree equation.  I wouldn't give that to someone in fourth grade.  [Alpha](http://www.wolframalpha.com/input/?i=%28x%2B1%29%5E-2%2B1%3Dx%5E-2) gets a mess $x = 1/2 (-1+\sqrt2+\sqrt{2 \sqrt2-1)}$
Comment: It looks like triangles BCF and DEF have $3$ identical angles and $1$ identical side, hence they are identical.
Comment: @barakmanos Similar, the hypotenuse are of differing length.
Comment: @DanielV: Yeah, I just noticed that (wasn't sure of the word to use though).
Answer: edit 1:
let $\cos{A}=x \implies \sin{A}+\tan{A}=1 \implies 1=\dfrac{1}{\sin{A}}-\dfrac{1}{\cos{A}}$
$\sin{A}\cos{A}=\cos{A}-\sin{A} \iff (\sin{A}\cos{A})^2=1-2\sin{A}\cos{A}$
let $u=\sin{A}\cos{A}\implies u^2=1-2u$
so you have one postive root $u_1$
$u_1^2=x^2(1-x^2),t=x^2>0 \implies t(1-t)=u_1^2$
now you have another positive root $t_1, x=\sqrt{t_1}$
Answer: here is partial answer:
we need to solve $(1 + \frac{1}{x})^2 = 1 + (1+x)^2$ on clearing you get the quartic $$ 0= f(x) = x^4 + 2x^3 + x^2 -2x - 1 = g(x) + h(x), \text{ where } g(x) = x^4 + x^2 - 1, h(x) = 2x^3 - 2x.$$
we are only interested in the solution $0 < x < 1.$ we can find a lower bound for $x$ this way. $g(x) = 0$ at $x^2 = \dfrac{-1+ \sqrt 5}{2}$  so the positive zero of $g$ is $\sqrt{\dfrac{-1+ \sqrt 5}{2}}$ and $h(x) < 0 \text{ on } 0< x < 1.$ by inspecting the sign of $g$ and $h$ we can conclude that the only zero of $f = g+h$ is $$\sqrt{\dfrac{-1+ \sqrt 5}{2}} < x < 1.$$

Euclidean Geometry challenge.


How to make series of test with protractor?

Question: What is canonical way to perform series of tests using protractor? Something like "visit every page on the list and check an aelemnt on it"? with a long list (hundreds/thousands of items) with all test results in one report?
Only way i am currently aware of is to supply varying part as a parameter and make humber of calls from the system (loop over the list of pages with awk, for example), which does not seem like a canonical way.
Comment: Could you please post sample Input_file and expected output please.
Comment: I feel there is no need for that, as i already have acceptable answer
Answer: You may look into using using() test "multiplier" from jasmine-data-provider:
var urls = ["url1", ... "url2"];

using(urls, function (url) {
    it("should do something with url: '" + url + "'", function () {
        // test logic here
    });
});


Train Stanford NER with big gazette, memory issue

Question: I have previously trained a german classifier using the Stanford NER and a training-file with 450.000 tokens. Because I had almost 20 classes, this took about 8 hours and I had to cut a lot of features short in the prop file.
I now have a gazette-file with 16.000.000 unique tagged tokens. I want to retrain my classifier under use of those tokens, but I keep running into memory issues. The gazette-txt is 386mb and mostly contains two-token objects (first + second name), all unique.
I have reduced the amount of classes to 5, reduced the amount of tokens in the gazette by 4 million and I've removed all the features listed on the Stanford NER FAQ-site from the prop-file but I still run into the out of memory: java heap space error. I have 16gb of ram and start the jvm with -mx15g -Xmx14g.
The error occurs about 5 hours into the process.
My problem is that I don't know how to further reduce the memory usage without arbitrarily deleting entries from the gazette. Does someone have further suggestions on how I could reduce my memory-usage?
My prop-file looks like this:
<code>trainFile = ....tsv
serializeTo = ...ser.gz
map = word=0,answer=1

useWordPairs=false
useNGrams=false
useClassFeature=true
useWord=true
noMidNGrams=true
usePrev=true
useNext=true
useSequences=true
usePrevSequences=true
maxLeft=1
useTypeSeqs=true
useTypeSeqs2=true
useTypeySequences=true
wordShape=chris2useLC
useDisjunctive=true
saveFeatureIndexToDisk=true
qnSize=2
printFeatures=true
useObservedSequencesOnly=true

cleanGazette=true
gazette=....txt
</code>
Hopefully this isnt too troublesome. Thank you in advance!
Comment: I would try using other ways to train the classifier http://www.chokkan.org/software/crfsuite/ might be faster than using Stanford's implementation of CRF (disclaimer: i haven't actually tested the speed to compare them)
Comment: Did you try [OpenNLP](https://opennlp.apache.org/)? My experience with StanfordNLP isn't so good: poor performance and results with OpenNLP have higher F score (of course, F score depends on your domain).
Comment: Thank you for your reply. I have cut the size of the gazette in half and training completed in about an hour. I had to disable almost all properties though, so the results were worse than without the gazette. So the speed isnt the main issue, the issue is that the process runs out of memory. I will have a look at that CRFsuite tho, so thank you!
Comment: I havent tried OpenNLP yet. I came across it when I decided which NER-tagger to use but I read that it has no implementation for german yet, which is why I am using the Stanford NER.
I was offered to use the PC at my universeity to train the classifier so I will try that with the full gazette & without disabling as many features and I will report back afterwards.
Answer: RegexNER could help you with this:
http://nlp.stanford.edu/static/software/regexner/
Some thoughts:

start with 1,000,000 entries and see how big of a gazetteer you can handle, or if 1,000,000 is too large shrink it down more.
sort the entries by how frequent they are in a large corpus and eliminate the infrequent ones
Hopefully a lot of the rarer entries in your gazetteer aren't ambiguous, so you can just use RegexNER and have a rule based layer in your system that automatically tags them as PERSON
Comment: My hope is a lot of your 16,000,000 entries are of the form rare last name, rare first name.  So you could add entries for all tokens that are rare last names (and don't have ambiguity) and rare first names (that don't have ambiguity) into your rule based layer as well.
Comment: Yes you are correct. An example line looks like this: ^PER\tFIRSTNAME\tLASTNAME$"
The problem is that there is a lot of ambiguity involved (i.e. Mercedes being a PER but also ORG, depending on context) so I wouldnt want a 100% direct tagging dictionary. I gathered from the FAQ that the dictionary would only help in the decisionmaking and not guarantee a tag, which is what I'm after. Edit: I misread what you said. This is not my trainingdata, I have an annotated 400k token file as trainingdata.This dictionary is meant to be an addition.
Comment: Thank you, those are some helpful hints. Especially that third point is definetly worth exploring!
Comment: You're absolutely right, this has been very helpful. Thank you! I will attempt to add the rare instances via RegEx and the more common ones via the gazette.
Answer: Heres an update to what I've been doing:
First I tried to train the Classifier using all available data on our universities Server with 128gb RAM available. But since the progress was incredibly slow (~120 Iterations of optimization after 5 days) I decided to filter the gazetteer.
I checked the german wikipedia for all n-Grams in my gazeteer and only kept those that occured more than once. This reduced the amount of PER from ~12 mio. to 260k.
I only did this for my PER-list at first and retrained my classifier. This resulted in an F-Value increase of 3% (from ~70,5% to 73,5%). By now I filtered the ORG and LOC lists as well but I am uncertain whether or not I should use those.
The ORG-list contains a lot of acronyms. Those are all written in capital letters but I dont know whether or not the training process takes capitalization into account. Because if it didnt this would lead to tons of unwanted ambiguity between the acronyms and actual words in german.
I also noticed that whenever I uses either the unfiltered ORG or the unfiltered LOC-list the F-Value of that one class might have risen a bit, but the F-Values of other classes went down somewhat significantly. This is why for now I am only using the PER-list.
This is my progress so far. Thanks again to everyone that helped.


Summation problem related to fractional part function

Question: Let $p$ and $q$ be distinct primes such that $\displaystyle \sum_{k=1}^{q} \left\{\frac{kp}{q} \right\}=51$. Find the unit digit of $q$.
Note that $\{a\}$ signifies the fractional part of $a$.
Comment: What have you tried? Please put your attempts in the body of the question; we will better be able to help you if you do so.
Comment: I tried to apply the property of greatest integer function. i.e {x} = x - [x], where [x] represents greatest integer function and {x} represents fractional part of x.
So, I have rewritten the given expression ∑{pk/q} = ∑pk/q - ∑[pk/q], for k=1 to q. But this doen't lead to any solution. May be some property related to prime numbers would be handful in this case, which I don't have any idea.
Answer: Let,
$S = \displaystyle \sum_{k=1}^{q} \left\{\frac{kp}{q} \right\}$
Since the summand is $0$ for $k = 0$ and $k = q$, we get,
$ S = \displaystyle \sum_{k=0}^{q} \left\{\frac{kp}{q} \right\} $
Change $k$ to $q-k$
$ \displaystyle \implies S = \sum_{k=0}^{q} \left\{p-\frac{kp}{q} \right\} $
$ \displaystyle = \sum_{k=1}^{q-1} \left\{-\frac{kp}{q} \right\} $
Note that,
$ \{x\} + \{-x\} = 1 \ ; \ \forall \ x \notin \mathbb{Z} $
$ \implies S = \displaystyle \sum_{k=1}^{q-1} \left(1 - \left\{\frac{kp}{q} \right\}\right) $
$ \implies S = q-1 - S $
$ \implies S = \dfrac{q-1}{2} $
Since $S = 51$
$ \implies q = 103 $
$ \implies q \pmod {10} = 3 $
Comment: As you point out, the value of the summand is $0$ for $k=0,q$ and you use that fact to shift among summation limits as it suits your proof. In the final step, you use summation limits of $1$ and $q-1$. I think your arguments should apply if those limits were $0$ and $q$, which would yield $S=q+1-S$ leading to $q=101$. I can't see a basis to distinguish which set of limits is arguably more appropriate. Can you say why one set of limits is correct or preferred? Note that neither set tracks the summation limits in the posed question, $1$ and $q$, so some change must be made.
Comment: Following on from my previous comment: numerical calculation shows that $q=103$ gives the correct answer (kudos to Robin) and $q=101$ (as well as several other values of $q$ tested as controls) doesn't; that fact does not help me understand why this should be so. I looked at about a dozen values of $p$, most but not all primes, and $q=103$ worked for all I looked at.
Comment: @KeithBackman The equation {x} + {-x} = 1 won't hold throughout the sum if the limits were $0$ and $q$.
Comment: Thanks for clearing that up for me.


Given a graph, identify users more likely to connect to a new user

Question: I have some twitter-like data described as tuples of users (u1, u2), that means u1 follows u2. I also have a second dataset with another list of tuples (r1, r2), that means user r1 frequently click on r2, yet does not follows r2. With these two pieces on data, I'd like to identify those r1 users from the second dataset that might be more likely to want to follow r2. In general terms, how do I go about approaching this type of problem?
Comment: What other variables do you have? I guess you must have a lot of covariables, and maybe a lot of data, such that it is practical  to divide the data in training and test sets.
Comment: The way I'm being asked to solve the problem limits the data to the graph tuples, and the frequent clickers tuples. I'm asked to make the most of it. I don't think this is a machine learning problem, more of a link prediction problem.
Answer: Without covariables, there do not seem to be much information.  If a specific $r_1$ do not appear at all as a $u_1$, then maybe he doesn't like to follow people, so the probability is low.  If he appears many times, maybe the probability is high.
So, some ideas.  For a specific pair of users $(a_1, a_2)$ you want the probability $p(a_1, a_2)$ that $a_1$ will start following $a_2$ at some future time (better specify when, or else will not be well defined).  Define three variables (for this pair):
$$   \\
   x=\text{number of times $a_1$ clicked on $a_2$}  \\
   y=\text{number of times $a_1$ appear as a follower of somebody, eg, as a $u_1$}  \\
   z=\text{number of times $a_2$ appear as being followed, eg, as a $u_2$}   \\
$$
will be some increasing function of $x, y, z$. You might try a logistic function, or something else.  Hope I have understood the problem well, at least this might be a start.
Comment: Unfortunately, I don't even have counts of clicks. I just know r1 clicked "many" times on r2. I understand this is coming across like a theoretical exercise, but this is the problem I'm tasked with. How about just looking at the number of common neighbors in the graph?
Comment: You can still do what I propsed, but with $x$ as a $0-1$ variable.


How to typeset a chord with variable note length in Lilypond?

Question: I am typesetting a score using Lilypond but I am struggling with the following bar:

I tried <fa la> <<fa4 {la8 sib}>> … but it does not render properly.
Global settings.
\version "2.20.0"
\language "italiano"

Staff settings.
\key fa\major
\clef bass

Comment: Since this wasn't called out specifically, you don't have "chords"; you have multiple independent voices, which Lilypond treats differently.
Answer: It looks like you could use some single staff polyphony.
The following should work; it sets up two voices, one with stems up, the other with stems down, so they can play/sing different rhythms.
\score {
    \new Staff <<
        \key fa\major
        \clef bass
        \new Voice = "first" { \voiceOne la4 la8 sib }
        \new Voice = "second" { \voiceTwo fa4 fa }
    >>
}

Output:
Answer: While Glorfindel's answer is correct, it's a bit long-winded. Depending on your needs and the rest of the score, you can get the exact same results by simply inputting
<<
    {
      la4 la8 sib
    }
    \\
    {
      fa4 fa
    }
>>

In other words, you can do this without all of the \new Voice = "this" and \voiceThat commands.
Answer: Modifying @Richard's answer.
Putting \relative do at the start of each voice keeps the voice in the same octave (in the second voice).
Using q to repeat chords is very useful.
<<
   \relative do' {
    la4 la8 sib do4 do8 sib |
   }
   \\
   \relative do {
    fa4 fa <fa la> q |
   }
>>

Answer: This was a little bit confusing to me so I'll post a full working example (kudos to @elements in space for the hint) as I had issues understanding basic sheet concepts
\version "2.24.1"
\language "espanol"
\score {
    \new PianoStaff <<
      \new Staff = "first" \relative {
        \key re \major
        re''8[mi]
        la[sol]
        fas4
      }
      \new Staff = "second" \relative {
        \key re \major
        \clef bass
        <la dos>4
        << { dos } \\ {la8[mi]} >>
        <fas dos>4
      }
    >>
}


Solr 6: how to group by title and return groups that contain minimum 5 numFound

Question: I want to group results by title which beginning with some letter:
&group=true
&group.field=title
&fq=title:A*
....

But, need only results that contain minimum 5 numFound.
How to query / filter in this case?
Answer: There is no direct way to do that in group query.
But you can do that by using facet.pivot like:
Note: Use only if you just need count not whole document.
...
&facet=true
&facet.pivot=title
&facet.pivot.mincount=5
...

But If you need Document while grouping then you need query two time.

The first one to get facet (where you get some titles which count grater then 5), eg.:
...
&facet.field=title
&facet=on
&facet.mincount=5
...

This query result is multiple value of of title which match with 5 same value in collection like:
11015 437027 412601

Then a second one for group:
...
&group=true
&group.field=title
&fq=title:(11015 437027 412601)
...

It will give you a desired Result.
Comment: @Salines As of my knowledge it is wrong syntax you need to put `:` separator between field and value or values here it is values separated by space and if it is string containing space it self the you need to put one vale in double quote.
Comment: i have typo in comments, fq=title:(111 OR 222)


scoped_session object has no attribute 'create_all'

Question: I have the following code that sets up my database with Flask-SQLAlchemy.  I'm getting an exception "AttributeError: scoped_session object has no attribute 'create_all'".  Can someone please explain to me why I'm getting the error and how I can fix it? :)
__init__.py:
from flask import Flask

app = Flask(__name__)
from app.db import DB

database = DB()
database.create_all()

db/__init__.py:
from flask import session
from flask.ext.sqlalchemy import SQLAlchemy
from app import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:pass@dburl:/schema'
connection = SQLAlchemy(app)

from app.db.models import *

class DB():
    def __init__(self):
         pass

    def create_all(self):
        connection.session.create_all()
        connection.session.commit()
        print("done")

models.py:
from app.db import connection as db

class Test(db.Model):
    __tablename__ = 'Test'

    id = db.Column("ID", db.Integer, primary_key=True)
    name = db.Column("Name", db.String(100), nullable=False)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Test: %s>' % self.name

Any guidance would be greatly appreciated!
Answer: It's connection.create_all(), you added session in the middle.

Unrelated to the immediate problem, there are other things that don't look right.

You don't need to commit after running create_all.
The extension instance is usually named db.  The DB class does nothing, just write your create_all function on its own.
You don't need to specify table or column names for Flask-SQLAlchemy models in most cases, and upper case names are not generally used.
Don't use tabs, PEP 8 recommends 4 spaces.


Retornar Valor setInterval

Question: Como é que consigo retornar um valor de um setInterval ?
result = setInterval(function () {
   var cont = i++;
   return cont;
}, 800);

Answer: A função setInterval retorna um id do intervalo (usado para posteriormente cancelar esse intervalo), logo você não deve usar return.
Você pode se valer de escopos porém conforme resposta do Pedro Luzio. Adicionalmente você pode utilizar uma IIFE para delimitar o escopo das variáveis.
var cont=0; // visivel em escopo "global"
(function(){
    var i=0; // visivel somente dentro do bloco
    setInterval(function () {
        cont = i++;
    }, 800);
})();

// alert(cont) funciona
/// alert(i) undefined

Answer: Terás de declarar a variável cont como variáverl global, pois o valor que a função retoma é o ID do intervalo...

i=0;
var cont=0;
setInterval(function () {
   cont = i++;
}, 800);
Answer: Tens de usar uma lógica assíncrona com callbacks.
Quando fazes
var result = setInterval(function () {
   var cont = i++;
   return cont;
}, 800);

a variável result guarda uma instância do próprio setInterval para poders parar ou cancelar. Mas para saberes o valor de cont, ou melhor para o usar em código tens de chamar uma outra função passando-lhe o valor que cont tem na altura que o setInterval é corrido. Ou seja, encadear o código para o próximo passo ser chamado no momento que o setInterval  está a correr a sua função.
Então terá de ser algo como:
function proximaFuncao(contagem){
    // aqui podes usar a variável "contagem" que irá ter o valor que "cont" tem no momento que esta função é invocada
}

var result = setInterval(function () {
   var cont = i++;
   proximaFuncao(cont);
}, 800);

Comment: Yap. boa solução aí
Comment: Eu só não percebo bem para que é o i neste contexto, não está especificado na pergunta. Se o objectivo for só o contador o i nem precisa de lá estar. Não nos foi explicado para que era
Comment: @Miguel pois, eu tb não, mas não mudei para só mudar o que tem a ver com a lógica assíncrona. Mas acho que o problema é o assincronismo.

Retornar Valor setInterval


Characterizing potentially non-differentiable functions by their maximum

Question: In short, my question – which has come up in a mechanism design setting I'm working on – is the following. Let $f,g\colon \mathbb{R} \rightarrow \mathbb{R}$ be continuous functions and let $f$ be non-decreasing and non-negative. Then for each $y\in\mathbb{R}$ consider the function
$$
r_y\colon \mathbb{R} \rightarrow \mathbb{R}\colon x \mapsto f(x)\cdot y-g(x)
$$
over $\mathbb{R}$. What do $f,g$ have to look like for $r_y$ to be globally optimal at $x=y$ for all $y\in \mathbb{R}$?
Of course, if $f,g$ are somewhat "well-behaved", we can go through the usual motions. For all $y$ it has to be $r_y'(y)=0$, i.e. $g'(y)=f'(y)y$ and via the fundamental theorem of calculus
$$
g(x)=C+\int_0^x f'(\zeta)\zeta d\zeta.
$$
But my calculus/real analysis knowledge is insufficient to understand whether the premises of the problem ensure that $f,g$ are sufficiently well-behaved or to understand what happens if they are not well-behaved.
Here are some more thoughts of mine. It's been a while since I took advanced calculus, so some of this might be confused.

Instead of talking about derivatives, we can talk about the (ratios of) differences. In particular, for all $d>0,y\in \mathbb{R}$, it must be $r_y(y+d)-r_y(y)\leq 0$ and $r_y(y)-r_y(y-d)\geq 0$. Rearranging stuff a little, this is equivalent to (for all $d>0,y\in \mathbb{R}$)
$$
y(f(y+d)-f(y))\leq g(y+d)-g(y)\leq (y+d)(f(y+d)-f(y)).
$$
This is nice because it's similar to the relationship between the derivatives. (Dividing by $d$ and letting it go to $0$ gives the relationship between the derivatives if they exist.) But it doesn't immediately answer questions about what kinds of $f$ are allowed or how to construct the corresponding $g$. (See below for problematic examples.)
Lebesgue's theorem for the differentiability of monotone functions seems to imply that $f$ and $g$ are differentiable almost everywhere. (The previous point implies that if $f$ is monotone, $g$ is monotone on $(-\infty,0)$ and on $(0,\infty)$.) So we can talk about the derivatives of $f$ and $g$ almost everywhere. But we might not be able to obtain (an "allowed") $g$ via integration of $g'(x)=f'(x)x$. For example, if $f$ is the Cantor function for $x\in[0,1]$, then
$$
\int_0^x f'(\zeta)\zeta d\zeta = 0,
$$
right (see, e.g., sect. 2 here)? But if $f$ is the Cantor function and $g=0$, then $r_{\frac{1}{2}}(\frac{1}{2})<r_{\frac{1}{2}}(1)$. That is, $r_{\frac{1}{2}}$ does not have a maximum at $1/2$. So can $f$ be the Cantor function? That is, if $f$ is the Cantor function, is there a corresponding $g$ (s.t. $r_y$ has a maximum at $y$ for all $y$) and if so what is the corresponding $g$? More generally, can $f$ be a function that we can't find by integrating its derivative and if so, is there a way of finding the corresponding $g$?
The above point asks whether $g$ might not be an integral over $g'$. Another question is whether $g'$ (or $f'$) must be integrable at all. Of course, there are continuous functions whose derivatives are not integrable, but the examples I am aware of aren't even monotone (not to mention our other requirements for $f,g$).
One standard move that people use to replace derivatives is to use sub-/super-derivatives. But that seems to require the functions in question to be convex/concave. But neither $r_y$, nor $f$ or $g$ must be convex/concave everywhere.
Answer: I think I found a solution via "standard" real analysis (no subderivatives, alternative integrals, ...).
By telescoping, it is for any $n\in\mathbb{N}_{>0}$
$$
g(\mu) = g(0) + \sum_{i=1}^n g\left(\frac{i\mu}{n}\right)-g\left(\frac{(i-1)\mu}{n}\right).
$$
Using the relationship between $f$ and $g$ in the OP it is
$$
\sum_{i=1}^n \frac{(i-1)\mu}{n}\left( f\left(\frac{i\mu}{n}\right)-f\left(\frac{(i-1)\mu}{n}\right)\right) \leq g(\mu) - g(0) \leq \sum_{i=1}^n \frac{i\mu}{n} \left( f\left(\frac{i\mu}{n}\right)-f\left(\frac{(i-1)\mu}{n}\right)\right).
$$
And now the lower and upper bounds can be interpreted as left and right Riemann sums for $f^{-1}$ for the partition $(f\left(\frac{i\mu}{n}\right))_{i=1,...,n}$. And then standard integration theory tells us that the lower and upper bound converge to the same value as $n\rightarrow \infty$:
$$
\int_{f(0)}^{f(\mu)} f^{-1}(x)dx.
$$
So $g(\mu)$ must also be that value plus/minus a constant.


Recent Projects panel on VS2008 not working for fresh installs

Question: The Recent Projects panel on the Start Page of VS2008 Professional doesn't appear to work, and constantly remains empty.
I've noticed this on 3 of our developers VS2008 installations, in fact all the installations that weren't updated from 2005 but installed from scratch. I generally treat this as a bit of a curiosity, but now I have a new laptop and fresh install of VS2008, it's also happening to me, and I've upgraded the phenomena from a curio to an annoyance.
Anyone know if this is a bug or if there is a setting I'm missing somewhere.
Thanks
EDIT Thanks, but Tools | Options | Environment | General | "items shown in recently used lists" was and is set to 6 by default
Comment: Never had that before, but could you check if the list in HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\ProjectMRUList is empty?
Answer: Is Tools | Options | Environment | General | "items shown in recently used lists" set to a number greater than 0?
Answer: Finally worked it out!
The recent projects is driven by (or at least shares a 'Show' flag with) the Recent Documents in the Start Menu.
For some reason our SOE has this hidden.
Both the following need th be set to 0:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoRecentDocsHistory HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\NoRecentDocsMenu
Comment: I can only navigate to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies, there is no Explorer Sub folder after that. (windows 7)
Comment: @Entrodus I'm fairly sure I was using XP when I posted this answer. Feel free to update it for Win7 and above if you work out an answer


PHP and JavaScript Buttons not working?

Question: My code (Below) works in Internet Explorer, but not in Chrome, Safari or Mozilla Firefox. Not sure why, but would it be possible for someone to point me in the right direction? This code has some buttons which change the form's action attribute and direct the data to different PHP controller file to do different things such as create user, modify user etc
JavaScript code:

PHP code:
<?php
    if ($authlib->auth_authobj($posting_userid,$_COOKIE['shost_app_id'],'002')>=2) {
        echo "<input type=\"button\" value=\"Create User\" class=\"formButton\" name=\"create\" id=\"create\" onClick=\"formAction('create')\">\n";
        echo "<input type=\"button\" value=\"Copy User\" class=\"formButton\" name=\"copy\" onClick=\"formAction('copy')\">\n";
    }
    if ($authlib->auth_authobj($posting_userid,$_COOKIE['shost_app_id'],'002')>=3) {
        echo "<input type=\"button\" value=\"Edit User\" class=\"formButton\" name=\"modify\" onClick=\"formAction('modify')\">\n";
        echo "<input type=\"button\" value=\"This button works\" class=\"formButton\" name=\"Working\" onClick=\"helloworld()\">\n";
    }
?>

Comment: Clean up your code first and narrow it down to the actual problem in it's simplest form. Also, using a framework like jQuery might help solve your crossbrowser problems.
Comment: So you're saying the "Hello World" function and alert work in all the browsers, but the `formAction()` function only works in IE? Do you get any error messages in the console? Have you tried putting an `alert()` or `console.log()` before and after the `switch` statement and after the `submit()`? That would at least tell you if the function is even being called and if it is breaking part-way through.
Answer: I assume that you have only one form on page. Your code has two errors.
1
To solve your problem, change all
  document.forms.useraction.action

to
  document.useraction.action

2
Also note that formAction is a reserved handler. You can not use formaction as a function name. Change the function name to formActionz or something else:
function formActionz(flag)

Answer: Following on from TheNoble-Coder's answer it might be better to restructre your code as follows:
var actions = {
    'create': '/apps/portal_admin/create_user1.php',
    'modify': '/apps/portal_admin/modify_user1.php',
    'copy':   '/apps/portal_admin/copy_user1.php#user2'
};

function formHandler(event)
{
    var target = window.event.target || window.event.srcElement,
        form = document.forms['useraction'];

    form.action = actions[target.name];
    form.submit();
}

fiddle: http://jsfiddle.net/AmmTZ/
jQuery
If your using jQuery, you can use the following code and avoid using onclick= on elements
$(function() { // Shorthand for $(document).ready

    $('[name=create], [name=modify], [name=copy]')
    .click(function() {
        $('form[name=useraction]').prop('action', actions[this.name]);
    });

});

PHP and JavaScript Buttons not working?


Can not change attributes of a button using CSS

Question: This is my index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Random quotes machine</title>
    <link rel="stylesheet" type="text/css" href="style.css">

    <button type="button" id="buttonAtt" onclick="newQuote()">New Quote</button>

And here's come my button attribute. There are more, but I cut it.
#buttonAtt {
    -moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
    -webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
    box-shadow:inset 0px 1px 0px 0px #ffffff;
    background-color:transparent;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-topleft:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:0;
    border:2px solid #ffffff;
    display:inline-block;

But the attribute of my button remains default, it doesn't change anything. Can you guys teach me?
Comment: The style you are using seems about right. Are the other styles in the stylesheet getting applied?
Comment: You have all colors set to white. Everything has been set, maybe you just cannot see it.
Comment: `newQuote()` where is the implementation to this method?
Comment: I use an image as background, so it should be ok if the colors are white
Comment: Perhaps my [answer](https://stackoverflow.com/a/49087563/7177029) may help you.
Comment: it's in the .js file
Comment: @BoyWithSilverWings the others work well, except this button, I don't know why
Comment: Try with setting only one attribute, like, set the color to red and see if it is getting applied
Comment: Check chrome devtools. Which styles are getting applied to the button?
Comment: no attribute is getting applied :(
Answer: I found one solution, but it doesn't make sense. I put an empty CSS attribute above the old one:
#buttonAtt{}

and it work well, don't know why...
Answer: My apologizes I read that wrong. Just give color to your box-shadows

#buttonAtt {
    -moz-box-shadow:inset 0px 1px 0px 0px #cccccc;
    -webkit-box-shadow:inset 0px 1px 0px 0px #cccccc;
    box-shadow:inset 0px 1px 0px 0px #cccccc;
    background-color:transparent;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-top-left:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:0;
    border:2px solid #cccccc;
    display:inline-block;
    }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Random quotes machine</title>
    <link rel="stylesheet" type="text/css" href="style.css">

    <button type="button" id="buttonAtt" onclick="newQuote()">New Quote</button>


Hypothesis testing based on Likert type data

Question: I know this site is full of similar questions, but either their answers do not apply, or I'm missing something.
I have data from a questionnaire. Responses are in the form of Likert items, some of which can be used to construct a scale. I'm specifically interested in those that cannot be used to construct a scale and should therefore be treated as ordinal.
One of the statements probes an employee's job satisfaction: I enjoy working at the company (answer: Strongly Disagree, Disagree, Neutral, Agree, Strongly Agree).
Another statement probes the employee's organizational fit (for example): I have several friends at the company (answer: Strongly Disagree, Disagree, Neutral, Agree, Strongly Agree). I have defined a hypothesis: Employees with a strong organizational fit will experience greater job satisfaction.
My questions are:

In order to reject (or not reject) my hypothesis, can I construct a contingency table and use either Pearson's Chi-square test or Fisher's exact test?
If not, can I use this data to test my hypothesis and how should I go about it?
If I can, how do I go about constructing the contingency table?: Should I take the response distribution to each statement (e.g. Job Satisfaction: SD = 35, D = 55, N = 40, A = ..., SA =...) and end up with a 5x5 contingency table?

If it matters, I'll be using either R or SPSS to perform the calculations.
Answer: (1) Yes you can, but nothing in either test takes the ordering into account. The ordered scales are reduced to nominal. The tests are applicable, but ignore much of the information you have.
(2) Many researchers would be happy to use rank correlation here. At least it respects the ordering of the categories. Many ties are likely, but that's par for the course. Another test that might be helpful is the Jonckheere-Terpstra test. A more ambitious analysis would be to use an ordinal logit or probit model. I wouldn't put all the weight on a single measure or test of association. Looking at a mosaic plot (spineplot) or two-way bar chart may help you see structure that's not directly expressed by a correlation. For example, on questionnaires some people give almost the same grades regardless of the question.
(3) The contingency table is the same regardless of what tests you apply to it. It's a $5\times5$ table of counts, as you say. It's not clear why you're asking this, not least because producing it is a simple task in any software.


How to use a method from an application in an activity

Question: I am trying to compare the answer of a method in my Application class and DBHelper class. I do this in an activity. While I can use the method of the DBHelper class, I can't access the method of my Application class
My application class:
<code> public class thing extends Application {

          private String thing1;
          private String thing2;
          private String thing3;
          private String thing4;

          public String getVariable() {
                  return thing1 + thing2 + thing3 + thing4;
            }
</code>
My activity:
<code>          public class solution extends AppCompatActivity {

               protected DBHelper DB;
                  @Override
               protected void onCreate(Bundle savedInstanceState) {
                 ...
                    }

                  }

            final Button solution = findViewById(R.id.solutionbutton);

            sol.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View v) {
                       DBHelper db = new DBHelper(getApplicationContext());
                       if(db.getDODO("two").equals(thing.getVariable())){
                           ....
                        }
         });
         }}
</code>
Comment: `thing` isn't a static class and `getVariable()` isn't a static method. that's why you can't call `getVariable()`
Answer: You can use method of the application:
<code>((thing) getApplication()).getVariable();
</code>


Unable to record video using this code base on python open cv

Question: Trying to record a video using opencv in python, i have used videowrite() method to record to record a video but i show the error. This error shows the 'an integer is required (got type noneType)'. Need a solution for this error.
import numpy as np
import os
import cv2

filename = 'video.avi'
frames_per_sec = 24.0
my_res = '720p'

def change_res(cap,width,height):
    cap.set(3,width)
    cap.set(4,height)

STD_DIMENSIONS= {
    "480p": (640, 480),
    "720p": (1280, 720),
    "1080p": (1920, 1080),
    "4k": (3840, 2160),
}
def get_dims(cap, res = '1080p'):
    width, height = STD_DIMENSIONS['480p']
    if res in STD_DIMENSIONS:
        width, height = STD_DIMENSIONS[res]
        change_res(cap,width,height)
        return width,height
VIDEO_TYPE = {
    'avi' : cv2.VideoWriter_fourcc(*'XVID'),
    'mp4' : cv2.VideoWriter_fourcc(*'XVID'),
}

def get_video_type(filename):
    filename, ext  = os.path.splitext(filename)
    if ext in VIDEO_TYPE:
        return VIDEO_TYPE[ext]
        return VIDEO_TYPE['avi']

cap = cv2.VideoCapture(0)
dims = get_dims(cap,res=my_res)
video_type_cv2 = get_video_type(filename)

out = cv2.VideoWriter(filename,video_type_cv2,frames_per_sec,dims)

while(True):
    ret, frame = cap.read()
    out.write(frame)
    cv2.imshow('frame',frame)
    if cv2.waitkey(20) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

Output:
Traceback (most recent call last):
  File "video.py", line 40, in <module>
    out = cv2.VideoWriter(filename,video_type_cv2,frames_per_sec,dims)
TypeError: an integer is required (got type NoneType)
[ WARN:0] terminating async callback

Comment: The `get_video_type` function returns `None` when the extension is not one of `avi` or `mp4`.
Answer: You are using os.path.splitext in get_video_type.
# filename = 'video.avi'
filename, ext  = os.path.splitext(filename)
# Now filename = 'video' , and ext = '.avi'

You are expecting ext = 'avi' which is not handled in get_video_type and returns None. Here is the link to doc of function.


I've been playing around with the strings method in Python and I was looking for some help in understanding the following behaviour:

Question: If we considered this input in Python:
s="""David Smith 17,15,14,19
     Melina Jackson 15,16,17,19
     Charli Decker 14,15,18,15"""

If we considered this string in 3 lines, and each line separated with "Enter" and some space between them, how could we this output:
{
    "David_Smith": 16.25,
    "Melina_Jackson": 16.75,
    "Charli Decker": 15.50
}

I want the result to be the average of the input numbers.
Comment: How is the numbers calculated?
Comment: Please read https://stackoverflow.com/help/how-to-ask. State clearly what you are trying to achieve and what you have tried so far.
Comment: average of numbers  @CutePoison
Answer: What you can do is :

Split the string every space. It will create a list with 3 elements per person : first name, last name and marks (I guess)

Iterate over the list. First we concatenate the first name and last name into Mark_Twain. Then we calculate the mean. Then we add this pair into a dictionary

def calc_mean(numbers: list[int]) -> float:
    """calculate a mean"""
    return sum(numbers) / len(numbers)

def extract_mean_from_string(s: str) -> dict:

    arr = s.strip().split(" ")

    means = {}

    i = 0
    while i < len(arr):
        name = arr[i] + "_" + arr[i + 1]
        string_numbers = arr[i + 2]
        numbers = list(map(int, string_numbers.strip().split(",")))
        means[name] = calc_mean(numbers)

        i += 3
    return means

# If we considered this input in Python:
s = """David Smith 17,15,14,19 Melina Jackson 15,16,17,19,20 Charli Decker 14,15,18 """

# I want to have this output:
expected = {"David_Smith": 16.25, " Melina_Jackson": 21.75, "Charli Decker": 15.75}

print(expected)
print(extract_mean_from_string(s))

{'David_Smith': 16.25, ' Melina_Jackson': 21.75, 'Charli Decker': 15.75}
{'David_Smith': 16.25, 'Melina_Jackson': 17.4, 'Charli_Decker': 15.666666666666666}

Those are the correct values.
Comment: If we considered this string in 3 lines, and each line separated with "Enter" and some space between them, how could we solve it?
Comment: @SeyedAmirVahabi  Assuming that you said enter is newline `"David Smith 17,15,14,19\n"` we can split this into lines using `"\n"`
Comment: @SeyedAmirVahabi Check I posted answer due to your edit in the question
Answer: Answer as you changed Question
Code :
s = """David Smith 17,15,14,19
Melina Jackson 15,16,17,19
Charli Decker 14,15,18,15"""

lines = s.split('\n')
mydict = {}

for detail in lines :

    newno = []
    items = detail.split(' ')
    nos = items[2].split(',')
    for s in nos :
        newno.append(int(s))

    avg = float(sum(newno)/len(newno))
    name = str(items[0])+' '+str(items[1])
    mydict[name] = avg

print(mydict)

Output :
{'David Smith': 16.25, 'Melina Jackson': 16.75, 'Charli Decker': 15.5}
Comment: Nice. Thank you!
Comment: we can complete it with these:
Comment: lines = s.strip().split("\n")
Comment: items = detail.strip().split(' ')
Comment: nos = items[2].strip().split(',')
Comment: @SeyedAmirVahabi Welcome ! If my answer fulfills your question you can accept my answer by clicking the check mark.
Comment: @SeyedAmirVahabi Yes. Simpler way


Reassigning a Java variable within a conditional

Question: I've got a variable, which is initialized and then dynamically reassigned in a conditional; as such:
int a;

if(b > 5) {
    int a = 10;
} else {
    int a = 1;
}

It gives me this error:
/path/to/file:4 a is already defined in int a = null;

Why can't I reassign this variable?
Answer: You're actually redeclaring variable a, not reassigning its value.
Try
a = 10;

instead of
int a = 10;

Answer: Good time to use the in-line conditional operator (the "ternary operator"):
 int a = (b > 5) ? 10 : 1;

Answer: When you write
int a;

this is the declaration of variable. And if you try to again write it the same way in the same scope and as the variable already exists so compiler throws an error.
You need not to re-define the variable a, just re-assign it like this:
int a = 0; // note that you need to initialize the local variables before using

if(b > 5) {
     a = 10;
} else {
     a = 1;
}

Comment: In this particular case, you don't need the full definition `int a = 0;`. Just `int a;` is okay. Personally I prefer doing just the declaration whenever possible.
Comment: IMHO, the re-assignment of the variable is actually even discouraged. Just declare it, then assign the value only once when you are sure of it.
Comment: ````int a;````     the compiler will always assign 'a' to 0


Vertical Sidebar Menu usando Bootstrap 3.3.2

Question: O meu problema é replicar algo parecido com isto. Estou com grandes problemas para resolver isto:
http://ironsummitmedia.github.io/startbootstrap-sb-admin/
A diferença é: sem palavras. Quando faço hover sobre a barra toda, aparece o resto da width a dizer o que é cada página (no fundo o que é cada icon). ter uma poisition fixed, ou seja, quando faço o scroll a barra não anda para cima nem para baixo, mas sim sempre no mesmo sítio.
E quando estiver mobile ter um efeito de lado e não de cima para baixo.
Alguém consegue ajudar? Obrigado.
Comment: Boa noite, sua pergunta é confusa, poderia ser mais claro? Edite a pergunta e tente ser mais objetivo e descritivo, de preferencia mantendo a organização do texto.
Answer: Para poderes ter uma navegação lateral onde só aparecem os icons e com rato por cima aparecem os icons e a legenda, precisas de um pouco de CSS para formatação e JavaScript para controlar se o rato está ou não por cima do menu de forma a apresentar as legendas.
CSS
A formatação, naturalmente, depende do layout da tua navegação, mas a parte importante é que o elemento que contém a legenda esteja escondido por defeito:
#sideBar > ul > li > a > span {
    display:none;
}

Saber mais sobre a propriedade display.
JavaScript
O segredo efetivamente está no código em baixo, que com recurso a jQuery simplificamos o processo de apurar se o rato está ou não em cima do menu:
$(document).ready(function () {
    $('#sideBar')
        .mouseenter(function () {
            $("a > span", this).show(); // rato entrou no menu, apresentar legenda
        })
        .mouseleave(function () {
            $("a > span", this).hide(); // rato saiu do menu, esconder legenda
        });
});

Saber mais sobre os métodos mouseenter e mouseleave.
Exemplo
Exemplo também no JSFiddle.

$(document).ready(function () {
    $('#sideBar')
        .mouseenter(function () {
            $("a > span", this).show();
        })
        .mouseleave(function () {
            $("a > span", this).hide();
        });
});
#sideBar{
    position:absolute;
    left:0;
    top:0;
    bottom:0;
    background-color:#222;
    padding:0 10px;
}
#sideBar > ul {
    float:left;
}
#sideBar > ul > li > a{
    color:#9d9d9d;
}
#sideBar > ul > li > a:hover{
    background:#080808;
    color:#FFF;
}
#sideBar > ul > li > a > span {
    display:none;
}

<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

  Dashboard

  Charts

  Tables

  Forms

  Bootstrap Elements

  Bootstrap Grid

  Blank Page

Sem JavaScript
Podes também atingir o mesmo comportamento apenas com CSS. Ver exemplo neste JSFiddle onde foi removido o CSS e adicionado a pseudo-class de CSS :hover para o menu:
#sideBar:hover > ul > li > a > span {
    display:inline-block;
}


Bound on sum of combinations

Question: I came across the following inequality $\sum_{i=0}^D \binom N i \le N^D+1$.
I am not sure how to prove this. I tried to do it by induction on $D$, and started with observing the values of sum for different values of $N$, and $D$. The values are as follows:
$$
        \begin{matrix}
        N \downarrow D \rightarrow  &0 &1& 2 &3 &4 &5& 6\\
        1 &1 &2& 2& 2& 2& 2& 2\\
2& 1& 3& 4& 4& 4& 4& 4\\
3 &1 &4 &7 &8 &8 &8 &8\\
4 &1 &5 &11 &15 &16 &16 &16\\
5 &1 &6 &16 &26 &31 &32 &32\\
        \end{matrix}
$$
Though form the base cases of $N=1, D=0$, and $N=1, D=2$, and so on, the inequality holds, but I am not sure how to proceed further. Any pointer on this would be great.
Answer: We shall prove the statement
$$\sum \limits _{i=0} ^D \binom N i \le N^D + 1, \ \forall N \ge 1, \forall \ 0 \le D \le N$$
using induction on $N$.
For $N = 1$, if $D = 0$ then $\binom 1 0 = 1 \le 1 ^0 + 1$, and if $D = 1$ then $\binom 0 0 + \binom 1 0 = 1 + 1 = 2 \le 1^1 + 1$. Thus, for $N = 1$ the statement is verified.
Let us assume it true for $N$ and let us prove it for $N + 1$.
If $D = N + 1$, then it is clear that
$$\sum \limits _{i = 0} ^D \binom {N + 1} i = \sum \limits _{i = 0} ^{N + 1} \binom {N + 1} i 1^i 1^{N + 1 - i} = (1 + 1) ^{N + 1} = 2^{N + 1} \le (N+1) ^{N+1} + 1 .$$
If $D=0$, the conclusion is trivial: $\binom {N+1} 0 = 1 \le (N+1)^0 + 1$.
For $1 \le D \le N$, using Pascal's formula $\binom {N + 1} i = \binom N i + \binom N {i-1}$ we have that
$$\sum \limits _{i = 0} ^D \binom {N + 1} i = 1 + \sum \limits _{i = 1} ^D \binom {N + 1} i = 1 + \sum \limits _{i = 1} ^D \left( \binom N i + \binom N {i-1}\right) = \\ 1 + \sum \limits _{i = 1} ^D \binom N i + \sum \limits _{i = 1} \binom N {i-1} = \sum \limits _{i = 0} ^D \binom N i + \sum \limits _{j = 0} ^{D-1} \binom N j \le N^D + 1 + N^{D-1} + 1 \le \\ N^D + D N^{D-1} + 1 + 1 \le (N+1) ^D + 1$$
as desired (we have used that $(N+1)^D = N^D + D N^{D-1} + \dots + 1$).
Comment: @SayanPal: Induction on $D$ doesn't really make sense: remember that induction is used when you want to prove that a property holds true for an *infinite* set of the form $\{ n_0, n_0 + 1, \dots \} \subseteq \Bbb N$. $D$, on the other hand, belongs to the *finite* set $\{0, 1, \dots, N\}$. Induction is meaningless for finite sets, therefore I have chosen to use induction on the single parameter running through an infinite set, and that was $N$.
Comment: Thank you for your answer. Additionally asking, is there a way this can be proved by induction on D?
Answer: We give a combinatorial argument that the sum from $1$ to $D$ (the number of non-empty subsets) is $\le N^D$.
Let $f$ be any function from the set $[D]$ of positive integers $\le D$  to the set $[N]$ of positive integers $\le N$. Let $i_f$ be the smallest number such that $f(i_f+1)=f(i_f)$. If there is no such number, let $i_f=D$.
For any function $f$ from $[D]$ to $[N]$, we can produce a choice $A_f$ of $\le D$ elements of $[N]$ as follows. The elements of $A_f$ are  all function values $f(i)$ from $i=1$ to $i=i_f$.
Every subset of $[N]$ with cardinality between $1$ and $D$ is $A_f$ for some $f$ (typically, for many $f$). The inequality follows.

Bound on sum of combinations


Views don't seem to be working properly on localhost with Chrome

Question: This seems to be something connected to being on localhost rather than a server as once the site is uploaded it works fine - it's almost as if Chrome is too fast for my drupal site. Parts of the views don't register properly (fields will be missing) but some of them do.
The site works fine locally on FireFox, IE and Safari - it's just Chrome. Any ideas?
Answer: I think your chrome cache is loading the 'old' page
clear your chrome cache:

when in chrome press shift+ctrl+del
then check ´Empty the cache´
click clear browsing data.

should be fixed now ;)
Answer: Clear your cached data and everything should be fine then.
If not, clear the site cache and the reload the page.
Also try updating the chrome.
Chrome is fast but not fast enough for drupal.


Input for onPrepareOptionsMenu

Question: I'm trying to make an app that disables the user from going to the menu. I know I have to override onPrepareOptionsMenu(Menu menu) but what do I have to put as input for menu if I want to use this function in a different function? I don't quite understand the Menu object and how many types it has.
Answer: Do something like this:
<code>private Menu mOptionsMenu;

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    mOptionsMenu = menu
    ...
}

private void updateOptionsMenu() {
    if (mOptionsMenu != null) {
        onPrepareOptionsMenu(mOptionsMenu);
    }
}
</code>
and then call the updateOptionsMenu() function where you want

Input for onPrepareOptionsMenu


How to calculate the expected pitch of the sound?

Question: My question comes from MUS 204, stating: If we know that the noise wave being looped is 128 samples long, and that the audio playback rate is 44,100 samples per second, calculate the expected pitch of the sound, and compare this to what you measure with a frequency meter.
(I believe samples per second, in other words, is cycles per second. Not completely sure.) I am unsure whether to divide 44,100 samples per second by 128 samples, finding the numbers of seconds, or leave the 44,100 samples per second as is and, if samples per second indicates cycles per second, equate the pitch to be 44,100 Hz. What do you think?
Answer: If you divide 44,100 by 128, you don't get the number of seconds- you get the number per second, (number of what? cycles, I'll get there...) which is the unit for frequency.  Look at your units- you have (samples/second)/samples => 1/second.  Then, you just need to look up what pitch this frequency corresponds to, using a table.
Intuitively, this makes sense because frequency is just cycles per second.  You are told that a cycle is 128 samples long, and a second is 44100 samples long.  How many cycles fit in a second?
The pitch is not 44,100- this answer results from not understanding what a sample is.    Your class notes or textbook will probably be the best place to read about this, but here is an additional online source.


Equivalent properties of integral domain f.g projective modules

Question: Question :
Let $R$ be an integral domain and $K$ be its fraction field. Let $M$ be an $R$ module. Then the following are equivalent:
(1) $M$ is projective $R$-module such that $[M\otimes_R K : K]$ is finite.
(2) $M$ is finitely generated and $M_{m}$ is free over $R_m$ for all maximal ideals $m$.
(3) $M$ is finitely generated and projective $R$ module.
Attempt :
I have proven the implications $(3)\implies (1)$ and $(3)\implies (2)$.
But I am not able to show any other implication. For example, for showing $(2)\implies (3)$, I don't think it is necessary to invoke the proof of the fact that finitely generated flat modules over integral domains are projective. I am not sure whether a simpler proof exists or not.
For $(1)\implies (3)$, I have no idea how to show M is finitely generated.
Any help would be greatly appreciated.
Answer: For $(1) \Rightarrow (3)$ choose $N$ such that $M \oplus N$ is free.  Let $X$ be a basis so that $M \oplus N \simeq R^{|X|}$, where here it's important to note that $R^{|X|}$ is a direct sum of $|X|$ copies of $R$.  Tensoring with $K$ gives $(M \otimes_R K) \oplus (N \otimes_R K) \simeq K^{|X|}$.  Now $M \otimes_R K$ is spanned by finitely many vectors which are nonzero in finitely many coordinates.  Projecting just to those coordinates we can assume $X$ is finite.  Then $M \oplus N$ is finitely generated so its quotient $M$ is finitely generated.
A good takeaway is to remember that a projective module is finitely generated if and only if it's a summand of a finitely generated free module.
For the locally free $\Rightarrow$ projective argument I know of no way to do it other than the standard arguments using flat modules, and those can be looked up in pretty much any commutative algebra reference.
Comment: Say you choose $N$ so that $M \oplus N$ has an infinite basis $X$, and order that basis so that $M \otimes_R K$ is supported in the first $n$ coordinates.  Then $M$ is supported in the first $n$ coordinates.  The homomorphism $M \oplus N \simeq R^{|X|} \to R^n$ which projects to these coordinates is injective on $M$ so if $N'$ is the image of $N$ under this homomorphism then $M \oplus N' \simeq R^n$.
Comment: I am sorry but I am not able to follow your argument on |X| being finite. How does projecting to those coordinates imply |X| can be assumed finite?
Answer: This is just a long comment about $(2) \implies (3)$.
Being flat is a local property, so, even disregarding finiteness, $(2)$ is immediately equivalent to  "$M$ is f.g. and flat".
Over most rings, it's not the case that finitely generated flat modules are projective, so I don't see how you can avoid 'invoking,' or proving for yourself, that f.g. flat modules over domains are projective.
That said, this follows immediately from the following result which everyone should have up their sleeve:

Proposition: Let $A \subseteq B$ an extension of rings.  If $M$ is an f.g. flat $A$-module and $M \otimes_A B$ is a projective $B$-module, then $M$ is projective.

This originated in On finitely generated flat modules, S. Jøndrup. For a self-contained exposition, I like Stenström's concise introduction to flat and pure modules in Rings of Quotients, chapter I, sections 10-11, where the result appears as 11.6.
To prove what you want over a domain, this is all you need, because when you extend the module $M$ to $M \otimes_R K$ you get a $K$-vector space.
Your result also follows from the characterization of f.g. projective modules as f.g. flat modules with locally constant rank function, see [Stacks Lemma 10.77.2(8)].  This is a really useful characterization and worth understanding.  Whenever a ring has finitely many minimal primes, the rank function is constant.
...Generalizing beyond domains...
More generally, it's not hard to show that finitely generated flat modules are projective over both semi-local rings.  For this, you might first cite a companion result to the previous one:

Proposition Let $A$ a ring with Jacobson radical $J$ and $M$ an f.g. flat $A$-module.  If $M/JM$ is projective as an $A/J$ module, then $M$ is projective as an $R$-module.

This is due to Vasconcelos in On Finitely Generated Flat Modules, Theorem 2.1.   From here the semi-local case is easy, having been reduced to showing that over a finite product of fields an f.g. flat module is projective.   Similarly, we get another way to see the result for rings with finitely many minimal primes.  If a ring has finitely many minimal primes, then its quotient by the nilradical $N(R)$ has its ring of fractions a finite product of fields, so $M/N(R)M$ is projective over $R/N(R)$. Then since $N(R) \subseteq J$, clearly $M/JM$ is projective over $R/J$, and the cited result implies $M$ is projective.
All in all these two basic results allowed us to deduce the following cute

Conclusion Let $A$ be a subring of a ring $B$ such that either $\operatorname{maxSpec}(B)$ or $\operatorname{minSpec}(B)$ is finite.  Then every f.g. flat $A$-module is projective.

Of course this subsumes the results about Noetherian rings and domains.

Bonus remark If $A$ is a ring such that $\operatorname{maxSpec}(A)$ or $\operatorname{minSpec}(A)$ is compact, then every f.g. flat ideal of $A$ is projective. (Here you need to interpret "compact" in the appropriate topology.)
Comment: Thanks for a detailed explanation. All the results you have stated are quite interesting. I will go through them.


Can the horseshoe prior be used with Beta(b, b) instead of Beta(.5, .5)?

Question: The horseshoe prior for, say, an unknown mean $\mu$ is expressed
$$
\begin{align*}
\mu_i | \lambda_i, \tau &\sim N(0, \lambda_i^2 \tau^2) \\
\lambda_i &\sim C^+(0,1)
\end{align*}
$$
where the prior on $\lambda_i$ can be equivalently stated as $\kappa_i := \frac{1}{1+\lambda_i^2} \sim$ Beta(.5,.5), and it is this distribution on $\kappa_i$ that has the horseshoe shape for which the scheme is named. In the normal mean model $y | \mu \sim N_d (\mu, I)$, the $\kappa_i$ say how much the MLE $y$ should be shrunk, and the philosophy of the horseshoe is that you want $\kappa_i$ to be near 0 to produce no shrinkage in signal components, or near 1 to produce strong shrinkage to 0 of noise components. Hence you'd like a prior on $\kappa_i$ that has its mass toward 0 and 1, like Beta(.5,.5).
However, Beta(b,b) for b in (0,1) will have the same horseshoe shape. $b$ approaching 0 will shift mass out of the middle toward 0 and 1, with limiting distribution Bernoulli(.5). $b$ approaching 1 will shift mass from the ends into the middle, approaching U(0,1).
Is there any work on using values of $b$ other than .5 in horseshoe priors? If so, what guides such choices?
Comment: The Bayesian way would probably be to put another prior on your $b$ and see what posterior Horseshoe you'd end up with given your data... :-)
Answer: In the subjective Bayesian paradigm, you always have a choice of priors, so obviously you can use that alternative prior if you want.  The only real issue here is whether or not you call that other prior a "horseshoe", which is really an aesthetic/terminology judgment, not a substantive statistical issue.$^\dagger$
As to what would guide the use of other types of beta priors with $0<b<1$ (compared to using $b = \tfrac{1}{2}$), presumably we would use $\tfrac{1}{2}<b<1$ when we want to be closer to a uniform distribution, and we would use a value $0<b<\tfrac{1}{2}$ when we want greater prior mass at the extremities.  In the context of the model you mention for signals, this would be a contextual judgment of how much we wish to favour values near zero or one a priori.

$^\dagger$ Incidentally, a rather silly aspect of the whole "horseshoe" terminology is the implicit assumption that the horseshoe can only be looked at in one direction (i.e., held so that it appears convex).  If you rotate the horseshoe 180-degrees it will then appear concave, so we could just as easily call concave priors "horseshoe" priors.  In fact, none of these priors actually look like horseshoes, since actual horseshoes rotate around to an extent that they do not even look like a function.
Comment: The limit as b goes to 0 is Bernoulli(.5) which produces a spike and slab prior, albeit a more strict version as the membership probability is strictly 50-50 rather than specified by its own prior. The spike and slab scheme suffers from exponential explosion of the search space (or so I understand) so I wonder if using small $b$ starts getting into these kinds of computational difficulties.


Added items to registration form and get "Notice: Undefined property: stdClass"

Question: I added 2 items to the user registration form Phone Number and Carrier. When I register a user or edit one i get the following error.
Notice: Undefined property: stdClass::$phone in user_account_form() (line 1066 of /var/www/capaug/modules/user/user.module).
Notice: Undefined property: stdClass::$carrier in user_account_form() (line 1076 of /var/www/capaug/modules/user/user.module).
Here is the code for the user registration:
<code>function user_account_form(&$form, &$form_state) {
  global $user;

  $account = $form['#user'];
  $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

  $admin = user_access('administer users');

  $form['#validate'][] = 'user_account_form_validate';

  // Account information.
  $form['account'] = array(
    '#type'   => 'container',
    '#weight' => -10,
  );
  // Only show name field on registration form or user can change own username.
  $form['account']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
    '#required' => TRUE,
    '#attributes' => array('class' => array('username')),
    '#default_value' => (!$register ? $account->name : ''),
    '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
    '#weight' => -10,
  );

  $form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

  //Phone Number Entry
  $form['account']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#maxlength' => PHONE_MAX_LENGTH,
    '#description' => t('A valid Telephone number. Numbers only, no parentheses or dashes.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->phone : ''),
  );

  //Carrier Selection
  $form['account']['carrier'] = array(
    '#type' => 'select',
    '#title' => t('Carrier'),
    '#options' => array(t('--- NONE ---'), t('AT&T'), t('NTelos'), t('Sprint'), t('Straight-    Talk'), t('T-Mobile'), t('Tracfone'), t('Verizon'), t('Virgin Mobile')),
    '#description' => t('Your phone service provider. Select "None" for home phones.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->carrier : ''),
  );
</code>
Where do I have to define those variables to get them to work?
Thank you all!
Answer: Never, ever patch core like that. This is not how Drupal works. That said, you didn't specify whether you are using Drupal 7 or not; I presume you do. Instead of doing this, use the field UI module to add the relevant fields to users under Administer > Configuration > People > Profiles.
Comment: Drupal 7. ANd how can I pull the information and combine it for a list of users in a certain role? Is it possible (once they have registered) to call the phone and carrier for every user in a list?
Comment: You want the Views module for the list. You really, really need to read more documentation or a book (http://shop.oreilly.com/product/0636920010890.do) on Drupal, these are very basic questions. As for calling... put up a different question. Finally, plz accept my answer if it was useful.


How to make a select form element with textfields for the array id and key?

Question: In a custom module which I'm working on, I have a select list which currently has a hard-coded array of key=>value which could change and I would like to expose these options to the user.
I would like to be able to have a select form element which contains one textfield for the user to enter the ID of the option and another for the user to enter the value of the option. I could make a separate form for these options, but I'd like to keep all the configurations on one page since there aren't too many.
Does anyone know how I can make a select form element where the key and value of each option is keyed in by the user?
Answer: Do you know of Drupal's core field type "List" or what it's called and its "Allowed Values" field? Where admins can enter key|value pairs divided by a pipe character?
It's exactly what you seem to describe.
I'd start by mimicking exactly that. But all in one form. Maybe multi-step. Maybe peppered with some Ajax...
Comment: Thanks! This seems right, but I decided not to pursue it, as the functionality wasn't worth the effort in the end.


Find a closest integer of form $3^x 5^y$?

Question: Given a arbitrary positive integer, is it possible to have a close-form solution of finding the closest (either smaller or larger) integer of form $3^x  5^y$, where $x$ and $y$ are non-negative integers? I can only think of using computer to search but wonder if it can be done better?
Comment: Use the computer, but be clever. First find $y$ such that $5^y\le n\le5^{y+1}$. Then repeatedly decrease the exponent on $5$ by one while finding the optimal exponent on $3$. That will be very efficient, and I suspect one can't do much better.
Comment: If we know an upper limit for the given number , we can also precalculate the numbers of the form $3^x\cdot 5^y$ (won't be too many) and with the sorted vector we can quickly find the best number (or possibly two best numbers).
Answer: It is easy to see that the $(x,y)$ that realize the closest integer must also realize the minimum of $n/ 3^x 5^y$ or the minimum of $3^x 5^y/n$, depending if it is above or below $n$.
These minima are equivalently found as $ \min \log n - x \log 3 - y \log 5$ and $x \log 3 + y \log 3 - \log n$ , in the region where the quantities are positive.
Now let $T := \{ (x,y): x, y \in \mathbb{N} \}$, and take the line $\ell := \{ (t, s) : (\log 3 ) t + (\log 5) s = \log n\}$. We are searching for the two closest point to $\ell$ in $T$ , one from the region above the line and one from the region below the line.
Note that the line intersect the axis at $\log_3(n), \log_5(n) $, which are bounded from above by $m= \log_3(n) $.
Below there is a mse answer where you have an algorithm described to solve this general problem, where at each step you change the line without changing the solution. There is a stated hypothesis that would mean $\log(n) $ small, but it is not used in the answer. The answer runs in time $\log m \simeq \log \log n$.
Diophantine approximation - Closest lattice point to a line (2d)
Also, let me notice that Gerry is right: I don't think you can do much better than $\log \log n$. Let $x_0, y_0$ be an integral solution to the closest to the line problem, and $x_1, y_1$ the projection of that point to the line. In particular it holds:
$$ (1) \ \  y_1 = - x_1 \log_5 3 + \log_5 n $$
$$ (2) \ \   |y_1 - y_0| \le 1/2 , |x_1 - x_0 | \le 1/2$$
(1) originally comes from $y_1 \log 5 + x_1 \log 3 = \log n$. In particular, we can suppose wlog $ x_1 \log_3 \le (\log n) /2$.
The second inequality comes from the fact that a line in a 1 times 1 square has a vertex which has distance at most $1/2$ in each coordinate.
The first equation implies, substituting $ x_1= [ \log_3 n ]  - x_1'$, that
$$ y_1 = - [\log_3 n] \log_5 3  + (\log _5 3)x_1' + \log_5(n) $$
Notice that the modulus of the constant term
$$  | [\log_3 n] \log_5 3 -  \log_5 n| = |  (\log_3 n +\epsilon(n) )\log_5 3 - \log_5 n | = |\epsilon(n) | \log_5 3 < 1/2$$
Because  the deviation  $[\alpha] - \alpha$ from a number to its closest integet is at most 1/2. Dividing by $x_1'$ we get
$$ | \frac{y_1}{x_1'} -  \log_3 5 | \le \frac{1}{2x_1'} $$
It's not hard to see that $|y_1/x_1 - y_0/x_0| \le 2/x_0 $ using the derivatives of $f(a, b) = a/b$, so that triangular inequality gives
$$ | \frac{y_0}{x_0'} -  \log_3 5 | \le \frac{5}{2x'} $$
This means that one between $\{ (y_0-2) /x'_0, .. (y_0+2) /x'_0\}$ is the closest rational number with denominator at most $x_0'$. (I could be wrong with specific numbers, there could be a 3 instead of a 2, but the principle is the same). Also, notice that $x_0' \approx x_1' \approx  \log_3 n - x >= (\log_3 n) /2 $ because of the WLOG assumption.
Up to my knowledge, the fastest way to produce rational approximants is to use continued fractions, that generally produce
a denominator $\approx 2^k$ in k steps, so that the number of steps to produce a denominator $q$ is $\log q$.
Since our problem produces a denominator $\log(n) $, it's running time should be at least $\log \log n$, as the Gerry algorithm (and mine above) does.
Comment: One may write this as log(n)/log(3) = x+y *log(5)/log(3). One may
introduce the sets of rational approximants for log(n)/log(3)
and log(5)/log(3) via the usual continued fraction method.
[Example: The converts from log(5)/log(3) =1.46497... are
22/15, 41/28, 63/43 , 230/157, 11673/1142, 5249/3583,..]
Each such pair of approximants leads to a linear diophantine equation
for the pair (x,y) after multiplication with the lcm of the two denominators of the approximants, which may have solutions (see Bezout's theorem...).
Answer: For any $n$, $b = \lfloor log_2(n) \rfloor$ is an upper bound for the exponents in its prime factorization. So, both $x$ and $y$ are bounded by $b$.
If your $b$ is small, you can just do an exhaustive search of $3^x5^y$ by varying $x, y$ between $0$ to $b$ and check them.
It is also true that $x + y$ is bounded by $b$. So, you can use that to make the search even more efficient.
Answer: Well, $3^3=27 = 2+5^2$.  I hoped I could find a "closer" pair of $\frac {3^k - 5^j}{\operatorname{avg}(3^k,5^j)} < \frac 2{\operatorname{avg}(27,25)}$ and maybe if I wrote a program I would have bout $3^3-5^2 = 2$ is pretty small.
For $n$ for $k,j$ so that $5^k \le n < 5^{k+1}$ and $3^{j-1} < n \le 3^j$. (If either are equal we are done and we can stop)
Check whether $5^{k-2}3^2$ (which is $5^k+2*5^{k-2}$) is larger or smaller then $n$ and check whether $3^{j-3}5^2$ (which is $3^j - 2*3^{j-3}$) is larger or smaller than $n$.
We will end that and every sequential step with a result that $3^{j'}5^{k'} \le n \le 3^{\overline j}5^{\overline k}$ for some $j',k',\overline j,\overline k$.
If you reach an equality you are done.  Otherwise repeat the step by comparing $3^{j'+3}5^{k'-2}$ to $n$ and $3^{\overline 3-3}5^{\overline k + 2}$.
If you never  hit an equality you will eventually reach some $j',k',\overline j, \overline k$ where $3^{j'}5^{k'}< n < 3^{j'+3}5^{k'-2}$ and $3^{\overline j-3}5^{\overline k+2}< n < 3^{\overline j}5^{\overline k}$ and $j'$ and $\overline j$ will be within three of each other and $k'$ and $\overline k$ will be within $2$ of each other.
We finish by comparing $3^{j'+1}5^{k}; 3^{j'+2}5^{k'};3^{j'}5^{k'+1}; 3^{j'+1}5^{k'+1};3^{j'+2}5^{k'+1};3^{j'}5^{k'+2};3^{j'+1}5^{k'+2};3^{j'+2}5^{k'+2}$ if necessary.


PHP - DateTime::__construct(): Failed to parse time string

Question: I am pulling DateTime timestamp result from another table which is set as:
When dumping specific value of $post->getUploadTime() I get:
"2602585961"

It's in string format.
In my entity I have modified the setter to:
public function setStartTime($startTime)
{
    $date = new \DateTime($startTime);
    $this->startTime = $date->getTimestamp();
    return $this;
}

And my code:
$newEntityObject->setStartTime(intval($post->getUploadTime()));

I am using intval() to transform string to integer (timestamp) so I can insert it in db but I get an error:

DateTime::__construct(): Failed to parse time string (2602585961) at position 8 (6): Unexpected character"

It's an error with or without the intval().
I can not figure out what is wrong?
I know there are a lot of posts about the issue. I tried them, but the problem still remains.
Comment: Where does that timestamp come from? Currently, the timestamp starts with 16, and the one you gave is 31 years from the future
Comment: Also, how is this related to Symfony? Please either explain the relation, or remove the irrelevant tags
Comment: Why do you have`\ ` before DataTime ? And I think DateTime consructor ask for `now` or the format date, not an int.
Source: https://www.php.net/manual/fr/datetime.construct.php
Comment: DateTime except an actual date for example '2021-06-30' not unix timestamp.
You could instantiate the DateTime class then use ->setTimestamp function on it.
Comment: @Elikill58 - I expect the `\DateTime` is because the posted source code is declared inside a namespace.
Answer: Try :
$date = new \DateTime();
$date->setTimestamp($startTime);
$this->startTime = $date->getTimestamp();

But since you are trying to assign a timestamp to your startTime property and you are already passing a timestamp to your function you can just assign whatever timestamp you are passing:
$this->startTime = $startTime;

Comment: Thank you but the given answer gives "DateTime::__construct() expects parameter 1 to be string, object given @kopz
Comment: The code in the answer does not pass any parameter to DateTime ...
Answer: You have a timestamp, and you are trying to make it a DateTime and get timestamp from the new datetime object.
The DateTime constructor only accept specific date and time format.
Also, the given value refer to the year 2052. So it's possible that you have another issue before.
Answer: You don't need to convert to a number. Because you need a string argument that starts with @
You need use @. Read Documentation.
 <?php

    $a = "@2602585961";

    function setStartTime($startTime)
    {
        $date = new \DateTime($startTime);
        $b = $date->getTimestamp();
        return $b;
    }

    echo setStartTime($a);

https://www.php.net/manual/ru/datetime.formats.compound.php
In your code:
$newEntityObject->setStartTime("@" .  $post->getUploadTime());

Comment: Thank you but the given answer gives "DateTime::__construct() expects parameter 1 to be string, object given @АлександрЧерножуков
Comment: @pohofo You must pass a string like "@2602585961" in your method
setStartTime
Comment: @pohofo for test do it $newEntityObject->setStartTime("@2602585961");


mariadb, PHP7 -- cannot grant all DB privs

Question: Within my PHP code, I've tried various iterations of this directive:
        $dbc->exec("CREATE DATABASE $dbName;
                    CREATE USER '$user'@'%' IDENTIFIED BY '$pass';
                    GRANT ALL ON $dbName.* to '$user'@'%' IDENTIFIED BY '$pass';
                    FLUSH PRIVILEGES;")

And, by iterations, I mean tweaking the db privilege values:

`$dbName`.*
$dbName.*
$dbName
'$dbName'.*
and so on...

For all attempts, I end-up with a user created with the GRANT USAGE statement and non-bound (associated) with the targeted database ($dbName).
The one and only time I've gotten this to work successfully is by changing the privilege levels to *.* which grants everything for all databases for this user which I am trying to avoid; I'd like to limit the grant to the named database only. Instead, when I exec a GRANT ALL, or GRANT ALL PRIVILEGES, of ending up with this result every time:
MariaDB [(none)]> show grants for someAdmin@localhost;
+-------------------------------------------------------------------------------+
| Grants for someAdmin@localhost
+-------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'someAdmin'@'localhost' IDENTIFIED BY PASSWORD '[snip]' |
+-------------------------------------------------------------------------------+
1 row in set (0.00 sec)

I've also tried restarting mariadb after issuing the commands just to see if the restart would force the correct privs but nope.
What's the correct SQL to grant all privileges on the database (with grant option) to the new user s.t. the user is actually granted all privileges on the named db?
(PHP 7.2, MariaDB 10.1, Ubuntu 18.04)

From the MariaDB Doc:
Global privileges are granted using *.* for priv_level. Global
  privileges include privileges to administer the database and manage
  user accounts, as well as privileges for all tables, functions, and
  procedures. Global privileges are stored in the mysql.user table.
Database privileges are granted using db_name.* for priv_level, or
  using just * to use default database. Database privileges include
  privileges to create tables and functions, as well as privileges for
  all tables, functions, and procedures in the database. Database
  privileges are stored in the mysql.db table.
Comment: SQL injections comment was pretty relevant as your code looks to be prone to that.. Which isn't a Opinion..
Comment: I'd suggest separating out each line into their own query, instead of passing it all as one. It may not be running all lines.
Comment: Mind the SQL injections? Also consider not making a MySQL user from application code as it is not safe..
Comment: Executing the queries individually produces the same results.
Comment: Opinion.  Neither relevant or useful.
Comment: For the rest of the pending a.r. commentary - please note this is just a simple stub and an incomplete one at that.  Forget about all the i-dotting and t-crossing and help with a solution instead of picking lint.  Thank you.
Comment: pretty sure by the way you are looking to the wrong MySQL account.. you run show grants on the  MySQL user that has  `localhost` as domain but you create/grant on the MySQL user which has `%` as domain/IP wildcard (can connect from everywhere assuming the OS firewall is also open on the MySQL port) in the statement..
Comment: Yup - that's my bad...as stated, several iterations.  Doesn't matter if I use '%', 'localhost', '*' or all of the above in multiple statements.  The results are the same.  mariaDB creates a user with GRANT USAGE instead of GRANT ALL to the targeted db.  Again, the challenge is to find the right syntactical combination to achieve the desired results without resorting to a global privilege grant statement.
Answer: This query combination worked for me:
            $dbc->exec("CREATE DATABASE $dbName;
                        CREATE USER '$user'@'$host' IDENTIFIED BY '$pass';
                        GRANT ALL PRIVILEGES ON $dbName.* to '$user'@'$host' IDENTIFIED BY '$pass';
                        FLUSH PRIVILEGES;")

The user is bound to the newly-created database with wildcard:{$dbname} permissions. Tunneling deeper, I see the user has all abilities, including the one to create indexes and db objects in the new database, except grant, which is what I was really needed.  Globally, the new user still has "usage" level permissions, also desirable.
Thanks for the questions and help - it got my brain kick-started to try different things!
Answer: '$user'@'%'
'someAdmin'@'localhost'

'%' does not include 'localhost', but rather everything else.
The normal pattern is
CREATE USER            'user'@'...' IDENTIFIED BY '...';
GRANT ALL ON 'db'.* TO 'user'@'...';
                       ^^^^^^^^^^^^
                       These must match exactly.

(In the old days, GRANT would CREATE the user; in the future (MySQL 8.0) it won't.  MariaDB will probably go that direction eventually.)
As for the ON 'db'.*, the dbname is optionally quoted.  (If not quoted, then beware of certain punctuation marks.)  The * is a wild card meaning "all of that db".
I think this context allows double quotes, single quotes, or backtics for quoting.
Comment: The user names in the sql directives do match, exactly.  I've tried several variations using single quotes, back-ticks, and no quotes, and it still fails to create db-wide privs instead granting usage privs only.  Initially the code creates two user accounts using localhost and '%' and then exec'd grant statements to both accounts.  This, of course didn't work properly prompting code reduction to a single user in an attempt to get that to work successfully.  Sorry but this is not an solution.  It should be if the code executed in-accordance with the doc.
Comment: @MichealShallop - And the "host" must match exactly.
Comment: @MichealShallop - Start over, list exactly and completely (except for pwd) the commands issued to create the account, plus the failed attempt to connect.
Answer: Have you tried to remove the "%" ?
It's better also to add localhost.
See this SO