CORONA SDK: How can I stop a loop with an event?

Question: In developing of my App, i have two problem  caused by the fact that I do not understand how to stop a loop with an event.
I have written the following code to replicate this problem.
In my App there is a complex model that takes up to two minutes of time to calculate the solution.
I would like to have the possibility to show the time that pass during the calculation and to stop or start again the calculation through the click on two differents buttons (in the code are two circles for simplicity).
How is visible from the following code, I can view the time passing and stop the loop only when the same loop is finished.
Someone has already had this issue?
Sorry for english.
Thanks for the tips that will come
regards,
Gianluca
local calculation_progress=true

local messagge_obj=display.newText("Start Calculation",display.contentCenterX-200, display.contentCenterY-200, native.systemFont, 40)
messagge_obj:setTextColor( 255, 255, 255 )

--- here there is a simple function, but in my App is a complex loop that works until 2 minutes
local function loop_fun()
    messagge_obj.text="Calculation started"
    local max_comps=1000000
    for i=1,max_comps do
        if calculation_progress==true then
            local messagge_loop=tostring(i) --- here is a simple model
            print(messagge_loop)
        else
            break
        end
    end
    messagge_obj.text="Calculation done"
end

--- setting of the timer
local test_time_label = display.newText("Time:", display.contentCenterX-125, display.contentCenterY-50, native.systemFont, 40 )
local test_time = display.newText("", display.contentCenterX-20, display.contentCenterY-10, native.systemFont, 40 )
local function refresh_time()
    local currentTime = os.date("*t")
    test_time.text=os.time( t ) --currentTime
end
Runtime:addEventListener("enterFrame",  refresh_time)

--- setting of play and stop button
local function play_calc()
    calculation_progress=true
    loop_fun()
    print("calculation_progress",calculation_progress)
end
local function stop_calc()
    calculation_progress=false
    print("calculation_progress",calculation_progress)
end
local myButton_calc_play = display.newCircle(display.contentCenterX+60,display.contentCenterY+200,60)
local test_play = display.newText("Play", display.contentCenterX+10,display.contentCenterY+180, native.systemFont, 45 )
test_play:setTextColor(0)
test_play:addEventListener("tap",  play_calc)
local myButton_calc_stop = display.newCircle(display.contentCenterX-100,display.contentCenterY+200,60)
local test_stop = display.newText("Stop", display.contentCenterX-145,display.contentCenterY+180, native.systemFont, 45 )
test_stop:setTextColor(0)
test_stop:addEventListener("tap",  stop_calc)

--- loop inside model
loop_fun()

Comment: Why are you using the loop with limit '1000000' :O. Is that for calculating time!!?
Answer: I'm not fully aware of your need. Is the following is what you needed?
local statusLabel
local calculation_progress = false
local timer_1

local messageLabel =display.newText("Start Calculation",90,90, native.systemFont, 20)
messageLabel:setTextColor( 255, 255, 255 )

local minVal = 02
local secVal = 00

local minLabel = display.newText("0"..minVal,130,120, native.systemFont, 20)
local secLabel = display.newText(":0"..secVal,160,120, native.systemFont, 20)

local function timerDown()
    secVal = secVal - 1
    if(secVal<0 and minVal<=0)then
        if(timer_1)then timer.cancel(timer_1) end
        statusLabel.text = "Play"
        print("Timer stopped... Calculation Finished...")
        return true;
    end
    if(secVal<=0 and minVal>0)then
        secVal = 59
        minVal = minVal - 1
    end
    secLabel.text = ":"..secVal
    minLabel.text = minVal
    if(secVal<10)then secLabel.text = ":0"..secVal end
    if(minVal<10)then minLabel.text = "0"..minVal end
    print(secVal)
end

local function myCalculationChanger()
    --[[I've assigned this to a single button,
        if you want, you can separate them --]]
    if(calculation_progress==false)then  -- First click to start
        calculation_progress = true
        statusLabel.text = "Stop"
        timer_1 = timer.performWithDelay(1000,timerDown,-1)
    else                                 -- Next click to restart
        if(timer_1)then timer.cancel(timer_1) end
        minVal = 02
        secVal = 00
        secLabel.text = ":"..secVal
        minLabel.text = minVal
        if(secVal<10)then secLabel.text = ":0"..secVal end
        if(minVal<10)then minLabel.text = "0"..minVal end

        statusLabel.text = "Play"
        calculation_progress = false
    end
end

local myButton = display.newCircle(0,0,60)
myButton.x = display.contentWidth/2
myButton.y = display.contentHeight-100
myButton:addEventListener("tap",myCalculationChanger)

statusLabel = display.newText("Play",20,20,nil,40)
statusLabel.x = myButton.x
statusLabel.y = myButton.y
statusLabel:setTextColor(0)

Keep coding.................. :)
Answer: Thank you very much for you reply and for your code posted.
But my intention is to exit from a calculation loop very long (until 2-5 minutes).
I have resolved it with a advice received in the COPROA SDK Forum
Below the code.
regards,
Gianluca

local calculation_progress=true

local messagge_obj=display.newText("Start Calculation",display.contentCenterX-200, display.contentCenterY-200, native.systemFont, 40)
messagge_obj:setTextColor( 255, 255, 255 )

--- function to exit from loop
function verify_progress_loop()
    local outcome=true
    if calculation_progress==false then
        outcome=false
    end
    return outcome
end

--- here there is a simple function, but in my App is a complex loop that works until 2 minutes
local max_comps=100000
local n_min_cicle=100
local n_delay=max_comps/n_min_cicle
local function loop_fun()

    local t

    local i=0
    local function doWork()

        for j=1,n_min_cicle do
            local outcome=verify_progress_loop()
            if outcome==true then
                local messagge_loop=tostring(i) --- here is a simple model
                print(messagge_loop)
            else
                messagge_obj.text="Calculation stopped"
                timer.cancel(t)
                --return 0
            end

            i=i+1
            if i==max_comps then
                messagge_obj.text="Calculation done"
                timer.cancel(t)
            end
        end

    end

    t=timer.performWithDelay( 0.1, doWork, n_delay )

end

--- setting of the timer
local test_time_label = display.newText("Time:", display.contentCenterX-125, display.contentCenterY-50, native.systemFont, 40 )
local test_time = display.newText("", display.contentCenterX-20, display.contentCenterY-10, native.systemFont, 40 )
local function refresh_time()
    local currentTime = os.date("*t")
    test_time.text=os.time( t ) --currentTime
end
Runtime:addEventListener("enterFrame",  refresh_time)

--- setting of play and stop button
local function play_calc(event)
    messagge_obj.text="Calculation started"
    calculation_progress=true
    loop_fun()
    print("Inside play_cal function")

    return true
end
local function stop_calc(event)
    calculation_progress=false
    print("Inside stop_cal function")

    return true
end
local myButton_calc_play = display.newCircle(display.contentCenterX+60,display.contentCenterY+200,60)
local test_play = display.newText("Play", display.contentCenterX+10,display.contentCenterY+180, native.systemFont, 45 )
test_play:setTextColor(0)
test_play:addEventListener("tap",  play_calc)
local myButton_calc_stop = display.newCircle(display.contentCenterX-100,display.contentCenterY+200,60)
local test_stop = display.newText("Stop", display.contentCenterX-145,display.contentCenterY+180, native.systemFont, 45 )
test_stop:setTextColor(0)
test_stop:addEventListener("tap",  stop_calc)

Answer: Use this code.
local t
local count = 1
local function loop_fun()
if calculation_progress==true and count<= 1000000 then
      messagge_obj.text="Calculation started"
      local messagge_loop=tostring(count) --- here is a simple model
        print(messagge_loop)
        count = count + 1
        t = timer.performWithDelay( 0.1, loop_fun)

else
      messagge_obj.text="Calculation done"
      timer.cancel(t)

end
end
and call the loop_fun() within stop_calc() after calculation_progress flag.


How to reduce screeching "string noise" when playing the guitar

Question: When I play some chords which are on the same strings but on different frets, I produce much string noise, when changing between them. For example take Eric Clapton's famous "Cocaine" riff, which can be played by the power chord sequence: E5, D5, E5.
I think the noise results mostly from too much pressure on the strings. I am wondering how I can reduce this noise but keeping the pressure on the strings in order to get a clean sound.
Comment: Acoustic or electric? You have 2 choices on electric, but really only one on acoustic.
Comment: @Tetsujin I am interested in both acoustic and electric variants.
Comment: Note that sound is also called "fret noise" for some reason.
Comment: disagree with the duplicate, linked question is about general left hand noise from high gain amplified playing, this question also refers to acoustic guitars and is more specific in the type of noise, meaning a good answer to the other question wouldn't be a good answer here and vice versa
Answer: It's difficult to comment on your individual technique without seeing it, so the most important thing is that you practice, and play very close attention to your sound while doing so.  Slow down your motions, and pay attention to what you are doing when you make the noise, and experiment, noticing how small alterations to your technique affect your sound.  Does the string noise reduce when you slow down your technique? Or when you play certain progressions as opposed to others?  If so, what is changing in your technique to cause that string noise.
Having said that, I can make a few guesses: a likely cause is that you are not relaxing your hand quickly enough between chord changes.  There should be an almost instantaneous switch between fretting and not fretting a chord, when you stop playing a chord your hand should relax instantly and your finger only be gently touching the strings.  This should still be a fluid motion not a jerky one, but it should happen quickly.  If this transition is less well defined, you may be dragging your hands across the strings with far more force than necessary: compare for example how much noise you make on the cocaine riff if you take the thumb off the back of the neck in between the change.  Obviously you would never play like this, but if it's significantly quieter, then that's an indication you are squeezing far too hard in between chord changes.
You may want to try practicing some styles with closed chords that require extensive muting, as this will help train your left hand to make cleaner, clearer chord transitions , something like this for example  is usually a good exercise for muting, but also might help you to reduce string noise by training your left hand.
If you still find yourself making more string noise than you like, you may also want to look at the equipment you're using: on both electric and acoustic guitars, new strings make far more string noise than worn in ones.  A brand new set of bronze strings on an acoustic will practically sizzle if you breathe on the guitar!  Some people like this, others not: it's personal preference.
So older, worn in strings will buzz less, and make less string noise.  More than that though, on electric gutiars, flat wound strings make pretty much no noise, because they're completely smooth.  If this is something that appeals to you, then you could investigate it.  They also have a different tone, which some people prefer.  For a "standard" rock tone rounds are the norm, but there is no harm in investigating other sounds: on the contrary it's a very positive thing for a developing musician to investigate things like this.
On an acoustic guitar, coated strings such as elixir polyweb produce much less noise.  Nanowebs and more modern coated strings show this effect much less, and one of the reasons that these were developed is that guitarists generally miss the noise!
Answer: For electric, you have two main choices...

Reduce the high frequencies on your amp, or reduce the amount of any compression you are using, or increase its release time .
Learn to lift your fingers higher as you make the transition.

For acoustic, your only real choice is the latter, learn to lift your fingers - though you could investigate less-bright strings or even one of those guitar string 'wipe' sticks. I haven't seen one in years, but there used to be a product called Fast Fret that would help reduce string noise.
A bit of Googling tells me it still exists... http://www.ghsstrings.com/products/11464-fast-fret?category_id=1964826-lubricants-cleaners
Bear in mind, if you don't like it, you'd probably have to change the strings.


Multi-track midi to sheet music

Question: I am looking for music software that has the following features.  I've looked extensively online.  There are many packages that can do midi -> sheet music.  However, I can't tell if they can do the following:

Record music line #1 midi to sheet music.
Manually edit line #1 to my liking.
Record line #2 midi to sheet music while listening to line #1.  I want the notes from #2 to line up rhythmically with line #1.
I can repeat this as many times as I want, to create a piece with many instrument voices.

I'm looking for someone who has actually done this with software and a keyboard.  What software did you use that had this functionality?
Comment: Any modern DAW with MIDI capabilities can do it. Or you can look for MIDI sequencers, which are like DAWs limited to MIDI functionality. Specific software recommendations are off topic however.
Comment: Regarding the recent update to the OP, the question was not closed as "opinion-based"; it was closed as "off-topic". More information about on-/off-topic questions can be found at [What topics can I ask about here?](https://music.stackexchange.com/help/on-topic).
Comment: I agree with the other comment: record your MIDI into a DAW, then export the midi (or even music XML if possible) into engraving software for the score/sheet music.
Comment: Although this could be seen as a request for product recommendations, it's an interesting question. Why is it still so difficult to work with musical notation when making music that people have to specifically ask for this capability? Why do we use these grids and rectangles etc. and written music is produced after the fact, and often it's not produced at all. The first products where you could record your playing and have it displayed as notation were... 40 years ago? What's the problem?
Comment: This would be a fast way to write software - improvise on the piano, clean up a little and bam,  you've got a musical score.  I also am disappointed that you have to use program A, then program B, then program C, etc.  Writing music interrupts the creative process; it's much nicer to capture in the moment.
Comment: I've rolled back to your first edit as meta information/arguments should not be in your question, but we can talk about it in chat or meta if you want. As Arron pointed out, it was closed because we don't do hardware or software recs. The real close message that should have displayed is "

Questions seeking recommendations for specific equipment are off-topic, because they are primarily opinion based. Instead, describe the required function and setting in which the equipment will be used, and ask what you should look for to achieve that."
Answer: This is possible.  It works best when you play very accurately - note starts and note durations - to a click.  Think 'Capture notation' rather than 'Capture performance'.   You can choose a DAW with a Score Edit page (e.g. Cubase) or a score publishing program with playback (e.g. Sibelius).
The two types of program have converged to an extent.   But only as much as e.g. Word has converged with InDesign.  Many documents could be prepared in either... but we still know which one we'd choose to lay out a book for printing.
Answer: Based on what you've said, there are a low of DAWs (Digital Audio Workstation) out there.
Here's a few list from what I know, could do that:
(These are free DAWs):

Garageband
MPC Beats (Though, I think it requires something. You could check it out here)
Musescore (Sheet music with MIDI capabilities. Add instruments to your liking. They play back the sound for example This person's arrangement
From what I know, these could as you said -- 1. Record a line in #1 2. Edit all of these notes to your liking 3. Line up rhythmically and add notes while you listen 4. Create a piece with many instrumental voices :)!!

Now for the DAWs that you have to pay for but are really good in terms of quality, expressiveness, and customization:

Reaper (Midi with notation viewing and editing capabilities with synth or electronic instruments)
Cubase (Midi with notation viewing and editing capabilities with synth or electronic instruments)
Logic (Midi with notation viewing and editing capabilities with synth or electronic instruments)
Sibelius (Music notation primarily with MIDI so mostly "acoustic" instruments)
PreSonus Notion (Music notation with MIDI as well)

Now, DAWs like Garageband or Reaper could look like the following:

You could see that the blue, yellow, and green rectangular shapes are when the instruments play. You could edit that by sliding them left or right, and adjust it rhythmically to the other instruments to your liking. Then as you could see on the bottom, there is the notation option if you would like to edit the notes.
Because the blue, yellow, and green rectangles (recordings) are on top of one another, you could hear them all at once when its played. These could be recorded through mic, Midi, etc.
And as for the link that I sent as an example for Musescore, those are like Sibelius or PreSonus Notation :)!
Answer: Depending on the quality of the features that you describe ("record" - how? "edit manually" - to what extent? do you need playback do you need? how much control over the layout? how professional the score?), you might get different answers.
The DAWs, in general, suck at typesetting scores (the newer ones usually don't even support score notation). The score typesetting programs - suck at real time recording and musical editing (if they even support it...).
Which is why, sadly the typical workflow involves using both a DAW and a typsetting package, usually you can get pretty good results using MusicXML files to move data between them.
Just playing things from a midi keyboard and having them become a score automatically - is a pipe dream; the gap between score notation and performance is just too big. Creating a score requires a lot of human interpretation. You need to be prepared to do a lot of manual adjusting after you play each part, unless the parts are very simple and you can afford to quantize them.
If I didn't want full control over the layout (say, I need to print the sheets for musician friends, not publish them), my workflow would be to use Cubase Pro (I also have experience with Finale, StaffPad, Dorico, very old Sibelius - but no idea about Logic Pro). The nice feature of Cubase Pro is that it separates the logical score from the performance, so you can, for example, adjust lengths of notes in the score - but keep the original length in the MIDI data. With some work you can make a project that sounds good and looks good.

Multi-track midi to sheet music


operator << overloading in c++

Question: I made this code
Declaration:
template <class T>
class Matrix
{
    std::vector< std::vector<T> > mat;
    size_t rows , cols;
public:

    Matrix<T>();
    Matrix<T>(const std::string);
    Matrix(const size_t r, const size_t c, const std::vector<T> v);
    Matrix<T> operator=(const Matrix<T> &other);

    friend std::ostream& operator<<(std::ostream &os , Matrix<T> m);
};

Functions:
template <class T>
std::ostream& operator<<(std::ostream &os , Matrix<T> m){

    for (size_t i = 0; i < m.rows; i++)
    {
        for (size_t j = 0; j < m.cols; j++)
        {
            os << m.mat[i][j] << " ";
        }
        os << std::endl;
    }
    return os;
}

Main :
int main(){
    std::vector<int> v(9);
    v[0] = 1;
    v[1] = 2;
    v[2] = 3;
    v[3] = 4;
    v[4] = 5;
    v[5] = 6;
    v[6] = 7;
    v[7] = 8;
    v[8] = 9;
    Matrix<int> m = Matrix<int>(2, 3, v);
    std::cout << m;
}

I get this error :

Error 1   error LNK2019: unresolved external symbol "class
  std::basic_ostream > & __cdecl
  operator<<(class std::basic_ostream

&,class Matrix)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$Matrix@H@@@Z)
    referenced in function _main  C:\Users\igor\documents\visual studio
    2013\Projects\matrix\matrix\Source.obj    matrix

I tried to write it without the friend but got a different error.
What am I doing wrong ?
Comment: I don't know if that as any thing to do with your problem (I don't think it does) but you should still have youre function take a `const Matrix&` instead of a `Matrix`
Comment: Since this is a template, the *definition* of `operator<<` must be `#include`d with the header.  Did you do this?
Comment: @IgorGumush define the templated operator directly in the header file, not in a .cpp file
Comment: http://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream
Comment: Is the definition in a .h file that is `#include`d in `main.cpp`? Posting an [MCVE](http://stackoverflow.com/help/mcve) will be very useful.
Comment: The .h file is included , I tried the other functions and they work fine.
Comment: Thanks , changed it but the problem not solved
Comment: `template` missing for Matrix declaration?
Comment: @vsoftco it's all in the header , the main is in .cpp
Comment: Sorry You all right , I copied the function into the class and now it's working
Comment: I provided an extensive answer to the different options for operator overloading (and friendship) for templates [here](http://stackoverflow.com/questions/4660123/overloading-friend-operator-for-template-class/4661372). Basically you can either befriend a template, a template specialization or a free function for the operator, but if you want to befriend a non-template function, you need to provide the definition inline.
Comment: @KennyOstrom: The linked question is about a non-template class. There are additional complications that are related to templates and not present in that linked question.
Comment: @5gon12eder: The friend function is **not** a template as declared, but a non-templated function. You do want to provide the definition in the header (whether you change the friendship to refer to a template or if you want to provide a non-template friend), but the statement in your comment is incorrect and might *teach* the wrong concepts to other people.
Comment: @DavidRodríguez-dribeas Good point, and +1 for your linked answer.
Answer: You must implement a template in the header-file, not only declare it there.
Unless, of course, you can explicitly instantiate all the needed specializations.
Anyway, consider defining your friend inline:
template <class T>
class Matrix
{
    //...
    friend std::ostream& operator<<(std::ostream &os , Matrix<T> m) {
        // do things
        return os;
    }
};

You won't be able to call it explicitly unless you also declare it in the containing scope, but ADL will find it, and that's all that you want anyway.

operator << overloading in c++


When does logistic regression not work properly?

Question: I need to find a situation in which logistic regression does not work well. Furthermore, I would like to know when a random forest might perform better than a logistic regression model.
Comment: try to make clusters of data in different locations (e.g. class 1 around (-1,-1) and (1, 1) and class 2 around (-1, 1) and (1, -1))- works good with dicision tress but not with logistic regression.
Answer: Consider these data (copied from @Sycorax's answer here: Can Random Forest be used for Feature Selection in Multiple Linear Regression?):

There are two aspects to the data in this figure.  First, the relationship is non-linear.  That isn't actually a problem for logistic regression properly specified.  In some cases, a logistic regression might fair better than a standard decision tree (cf., my answer here: How to use boxplots to find the point where values are more likely to come from different conditions?, although vis-a-vie a random forest is more ambiguous).  The bigger problem is that there is complete separation at the decision boundary.  There are ways of trying to deal with that (see @Scortchi's answer here: How to deal with perfect separation in logistic regression?), but it adds complexity and requires considerable sophistication to address well.  I think a random forest would handle this as a matter of course.
Comment: @hxd1011: This is all fine in the above example given the trivial transformation you can apply. However in higher dimensions, especially when your clusters of classes are considerably more complex and have different separation widths, this becomes considerably more complex.
Comment: +1 good point. But after feature transformation, e.g., polynomial expansion or kernel PCA, logistic regression will work well.
Comment: @Sycorax, beat you to it ;-)!
Comment: Hah! I came here to write exactly this. +1
Answer: The answers so far emphasize the predictive failure of logistic regression. However there's also issues of poor feature importance/inference. For example, when your classes are highly correlate or highly nonlinear, the coefficients of your logistic regression will not correctly predict the gain/loss from each individual feature. In gung's example, if you were to train a logistic regression on the picture of points shown, it will likely create a linear split somewhere in the middle of the red region (for example a vertical line), implying that an increase of say, $x_1$, will lead to a higher probability of being a red class, which is true for $x_1$ starting to the left of the prediction boundary, and false for $x_1$ starting to the right.
Comment: FWIW, my point was that you needn't fit a LR model composed of linear (in the log odds) functions of X1 & X2.
Answer: @gung had a good answer. Logistic regression is a linear model, so it may not work well on non-linear cases. But as I mentioned in the comment, it might be some ways to transform data into another space, where logistic regression will be good again, but finding the basis expansion / feature transformation may be not trivial.
Essentially, certain model will work well when the data satisfy the assumption of the model, e.g., if the decision boundary is linear, then logistic regression will work well.
On the other hand, I would strongly recommend you to review bias variance trade off.
In terms of model complexity, logistic regression has high bias and low variance. And random forest is opposite. Which means, in general, logistic regression will preform with "less accurate" but "more stable", and random forest is opposite.
Comment: You should read the full discussion in my linked answer that @gung linked to. If you know exactly what the functional form is, basis expansion is viable. But the form of the expansion is not automatically suggested. Moreover, the stability of random forest can be improved by increasing the number of trees and enforcing minimum sizes on terminal nodes/splits. However, RF is very weak when it has to *extrapolate.*
Comment: @Sycorax thanks for Alex R. and your comments. I revised my answer.
Answer: A simple example for a case when logistic regression can't work properly:
https://towardsdatascience.com/when-logistic-regression-simply-doesnt-work-8cd8f2f9d997
Comment: Welcome to the site. We are trying to build a permanent repository of high-quality
statistical information in the form of questions & answers. Thus, we're wary of
link-only answers, due to linkrot. Can you post a full citation & a summary of the
information at the link, in case it goes dead?
Answer: Situations where features combined effect on response are not linear.
Imagine you try classifying documents as pet related or not per related.
You have two features -
* Number of words in the document(X1).
* Number of times the word Dog appears in the document(X2).
Intuitively, X2/X1 is a good way determining a document's class.
This is not a linear relation, so where tree like models can use a:
If X1>10:
      if X2>5:
         Pet related
   else:
      Not Pet related
A logistic regression will have no such option, and will result in model described by
if aX1 + bX2 > Z:
 Pet related
else:
 Not Pet related
For some Z.


How can I set the default value for an HTML  element with JavaScript?

Question: How to set the 'selected' (default) value for an HTML <select> element with JavaScript. Aka. currently option0 is 'selected', how to run a script to change it to display the value i want?
this for example because that value is previously saved in a database, and i only want it updated if the user actually specifies to do so. But if i don't specify the value (by re-selecting the previous option), saving the 'edit' will overwrite the previous value with the 'default selected' value the <select> is loaded with.
<select id="selector" name="selector">
  <option id="option0" value="0" selected=true >default </option>
  <option id="option1" value="1">option 1 </option>
  <option id="option1" value="2">option 2 </option>
  <option id="option1" value="3">option 3 </option>
  <option id="option1" value="4">option 4 </option>
</select>

NOTE: Because i lack reputation to add my answer (below) to the general thread on this topic, here the solution i got to using javascript, to set an option to be the option displayed/selected in the selector. This can also be a <%= value %> from a database.
Comment: Does this answer your question? [How do I programmatically set the value of a select box element using JavaScript?](https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript)
Answer: Use value property to set new selected value using JavaScript

document.getElementById('selector').value="2";
<select id="selector" name="selector">
  <option id="option0" value="0" selected=true >default </option>
  <option id="option1" value="1">option 1 </option>
  <option id="option1" value="2">option 2 </option>
  <option id="option1" value="3">option 3 </option>
  <option id="option1" value="4">option 4 </option>
</select>
Answer:

We get all the options (this is an html collection) and iterate over it to check if any option is equal to the "String" or "<%=string_value_from_database%>". And set it's .selected to true.
NOTE - MAYBE BETTER - DEFFO SHORTER:  with help in the comments:

Where to_select.value is either set to the value you want, or to a database value. Do note, you may or may not need the ".." around the value you set, depending on the setup of the <select> and how you stored your data.
Comment: There's no need for all of that. If the `select` does not have the `multiple` attribute, you do not need to set any other `option`'s `selected` property to false before setting another's to true. You also don't need to loop; just set the value of the `select` element to the value retrieved from the database, as noted in the answers to the question linked in the comment to the question.
Comment: See, that first thing is definitely something you need to know (i edited it out, from my answer), i tried it and it works in my case :) ... i will check the code you linked to as well.
Comment: Ok, i managed to make that code work, but i had to add ".." around my the database call to have it update in the html selector on screen correctly (otherwise it said the data from the database was 'undefined'; aka it treated it as some variable).
Comment: @HereticMonkey tnx for your time and attention, i'd give a rep if i could? ... anyways, i included the answer you linked to with the note that i ran into myself.
Answer: use this
document.getElementById("selector").selectedIndex = 3;

original
Comment: Please don't answer duplicate questions. Instead, flag them as duplicates, giving the URL of the duplicate question (the "original" link in your answer).
Comment: @HereticMonkey See, i can't add my answer to these questions, because i lack the reputation to do so, but i don't see my answer as one of the answers given... while for me the answer i provide (see my name in the list of answers) is the one i needed. So seeing stackoverflow doesn't let me provide the answer, the only way for me to help somebody else is to do it like this...
Comment: @Arghore You can add your answer to the question I linked to. Anyone can; there is no lock on that question.
Comment: @HereticMonkey --- I see: Highly active question. Earn 10 reputation in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity. ;) ... so i can't :(
Comment: @Arghore Argh; sorry, this is part of a bunch of changes Stack Overflow has been making. I don't see that message because I have more rep, so I didn't think it was locked like that :(. That's annoying...
Comment: @HereticMonkey it's ok i'll get the rep eventually :) tnx anyways for your understanding and your help.


Twig template file not recognized

Question: I have a page-view that prints "Fields" as "unformatted list". I am trying to name my view after adding the below suggestion on the .theme file:
function mytheme_theme_suggestions_views_view_fields_alter(array &$suggestions, array $variables) {
  $view_name = $variables['view']->id();
  $view_display = $variables['view']->current_display;
  if ($view_name && $view_display) {
    $suggestions[] = $variables['theme_hook_original'] . '__' . $view_name . '__' . $view_display;
  }

According to the suggestion the twig file is named as : views_view_field__my_view__page__1.html.twig
But the template is not getting recognized. View name is my_view. Can someone help on correcting my view twig template name?
Comment: do you return the $suggestions array? Also double check the spelling in the function name MYMODULENAME_theme_suggestions_views_view_field_alter
Answer: You can disable the cache and enable debug mode with this instructions.
Besides, you can confirm that your param in the hook is OK:

Dont forget to rename mytheme for your real name in the function.

Twig template file not recognized


Can a) and b) real components of an complex equation?

Question: I have a problem somewhere ...  I missed a point..
So given are following equations: (with $C \to R$)

(i)  $a(z) = x^2 - y^2$

(ii) $b(z) = x^2 + y^2$

And I am supposed to find out if those equations could be the real component of an complex equation ($C \to C$)
I used the Cauchy Riemann equation which gave me

(i) $2x=0$ and $-2y=0$
(ii) $2x=0$ and $2y=0$

Both just work for $x = y = 0$
But this would mean $z = 0$ right? So neither of them can be a component of an complex equation (as in complex differentiable function) right?
Comment: What you probably mean is if $a$ or $b$ can be the real part of an *analytic/holomorphic* function. But how did you come up with the equations $2x=0$ and $-2y = 0$??
Comment: I just got more confused tbh :(
Comment: as said I used the CR equations.. with the whole u(x,y) and v(x,y) but v(x,y) is 0 since we want to know about the real component.. And the exercise cleary states: 'find out if a or b can be a real component of a complex differental function in C'
Comment: OK, so you mean a complex differentiable function. That is not mentioned in the question. But *how* did you use the CR equations. There must be an error in your calculations.
Comment: To amplify what Martin said: for a), let $u(x,y)=x^2-y^2$, and see if you can find a $v(x,y)$ so that u and v satisfy CR. For b), do the same, but with u being $x^2+y^2$.
Comment: v isn't zero, it's an unknown function you need to try to solve for.
Comment: but the exercise doesn't care about the imaginary part? I should show if a or b can be in an complex function as the real component?
Comment: It cares about it; it just doesn't know it. And it wants you to care about it too (:-)), and it wants you to find it, (if you can).
Comment: v should be 0 since there is no i in the equation at all which should mean the imaginary part should be iy = 0
Comment: Oh, and yes "I should show if a or b can be in an complex function as the real component" is exactly right.
Comment: Suppose i asked you "Can $1$ be the real part of a square root of $2i$?", what would you do?
Comment: but sqrt(2i) isnt real? its the imaginary part of z and not the real...
Comment: Again: Please show (in your question, not in the comments) *how* you applied the CR equations. We cannot tell where your error is until we see what you did (wrong).
Comment: Yes, sqrt(2i) isn't real, it has to be imaginary. Let's step back - can you write me an imaginary number that has a real part 1? Just pick some arbitrary one.
Comment: differentiate the function a(z) with respect to x is 2x and to y is -2y and as i stated  the imaginary part is 0, so it is its derive...
Comment: The imaginary part is not zero.
Comment: why not? as far as I learned there need to be an i somewhere to be counted as imaginary part
Comment: I'm sorry, but I've got to head out. Hopefully Martin can help you. Good luck!
Comment: i don't understand the imaginary part... when I look at i) and search for the imaginary, it ends with a(z) = x^2 - y^2 (+/- iy) with iy= 0? is that not correct?
Comment: $$\frac{\partial v(x, y)}{\partial x} = \pm 2y
\\ \implies v(x, y) = \pm 2xy + f(y)
\\\frac{\partial v(x, y)}{\partial y} = 2x
\\ \implies  \pm 2x + f'(y)= 2x
 $$
in one case $f(y)$ has no solution hence $v(x,y)$ does not exist, in the other $f(y)$  could be any constant so  $v(x,y)$ does exist.
Answer: Based on the information you gave in the comments section, i assume that the exercise's question migth be rewritten as:
Figure out if the real-valued functions $\{a;b\}:\mathbb{C\rightarrow R}$, given by:
\begin{array}
\\a(z)=x^2-y^2
\\b(z)=x^2+y^2
\end{array}
with $z=x+yi$, can be the real part $\Re(f)$ of a complex function $f:\mathbb{C\rightarrow C}$.
With these premises, the exercise has a defined answer:
Let $f_a$ and $f_b$ be complex functions. If we let:
$$f_a(z)=z^2=x^2-y^2+2xyi$$
We see that $\Re(f_a)=a$, so $f_a$ exists.
Likewise, if we let:
$$f_b(z)=|z|=z\overline{z}=x^2+y^2$$
Wich is it's own real part, so $f_b$ exists too. In other words both $a$ and $b$ can be the real part of a complex function $f:\mathbb{C\rightarrow C}$.
As for the cauchy-riemann equations, you're using them the wrong way. For the equations to work, you need the initial function $f(z)$ to be able to decompose to the form:
$$f(z)=u(x;y)+iv(x;y)$$
Comment: Hmm, because the CR equations were mentioned, I think we all assumed the function was supposed to be analytic. But I see that that's not a requirement that is stated. In which case $f_a(z) = Re(z)^2 - Im(z)^2+0i$ works just as well.
Comment: (I don't think the function I gave in my comment is a very good answer, which is why I'm betting that analyticity is a requirement, but the OP forgot to mention it. But I certainly can't be sure about that.)
Comment: I'm guessing that the OP wrote down the exercise in a form that differs from the original source. He mentions equations from $X$ to $Y$ $(X\rightarrow Y)$, but equations do no possess a domain or codomain themselves.
Comment: I promise I copied the exercise word for word, so for Jonathan missing its analyticity ??  the only confusion i have or had from the start was that the lecturer told us one (a or b) works and the other doesn't and we are on topic of the CR-Equation, thats why I thought it was important to solve the excercise with these...
Comment: Well… it is still an ill-stated excercise. As i mentioned on my earlier comment, there is no such thing as an equation with domain and image (this is, an *equation* $(X\rightarrow Y)$ does not make sense). If you interpret the word "equation" to be "function" whenever this problem appears, (wich is a more or less legit interpretation), you are only left with a problem of existence of the functions $f_a$ and $f_b$ mentioned on the answer.
Comment: i will come back if i know the answers!
Comment: So bascially I was supposed to differentiate the function a(z) with respect to x (parallel to y) two times and look if a(xx) + a(yy) = 0, which fits for a(z) but not for b(z)..


C program to read alternate characters from file using system calls not working in loop

Question: I made a program that read alternate characters from a file passed as terminal argument and print it on terminal. The program is:
#include<stdio.h>
#include<unistd.h>

int main(int argc, char * argv[])
{
    int fd = open(argv[1]);

    if(fd>0)
    {
        char content[1];

        while(read(fd,content,1))
        {
            write(1,content,1);
            lseek(fd,1,SEEK_CUR);
        }
    }
    else
    {
        printf("File could not be opened.\n");
    }

    return 0;
}

But it is printing characters in weird pattern. But when I just used that code by repeating it one after other, it is printing alternate characters. Here is what is working:
    read(fd,content,1);
    write(1,content,1);
    lseek(fd,1,SEEK_CUR);

    read(fd,content,1);
    write(1,content,1);
    lseek(fd,1,SEEK_CUR);

    read(fd,content,1);
    write(1,content,1);

My input file:
abcdefgh
ijklmnopq
rstuvwxyz

Output I am getting:
ikmoq
suwy

By alternate characters I mean skipping 1 character.
That code is printing 3 alternate character from the file but the loop prints different characters from the second character itself. Where am I going wrong? Why is the repeating code working and loop not?
Comment: [`open` requires at least one more parameter.](https://pubs.opengroup.org/onlinepubs/9699919799/) It should be `open(argv[1], O_RDONLY);`. And you should include ``. Did your compiler not warn you? Recompile with '-Wall' or '-Wmost' to enable more warnings. With the corrected `open` call and the added include, the program works for me in a simple test; it prints alternate characters from the input file.
Comment: @ShantanuShinde also compile with `-Wall` and treat the warnings as errors.
Comment: @EricPostpischil but the programing is not giving any errors. Open is working as it is supposed to.
Comment: The program works fine if the 'open' error is corrected.
Comment: If you compiled the code shown, then your compiler may have compiled a call to `open` with an old default declaration. This resulted in a call which passed only one argument. The actual open requires at least two arguments. So it received uncontrolled data for the second argument. That might have resulted in opening the file in some undesired mode. Or it might have corrupted your program's call stack. The behavior of calling a routine with a declaration not matching its definition is not defined by the C or Unix standards. Your program is broken. Fix it. I showed you a correct call.
Comment: @EricPostpischil I did that. still not getting alternate characters.
Comment: @ShantanuShinde please post a [mcve] (that is the exact code you compile). What is your platform and compiler? Also show a minimal input file and the expected output.
Comment: Update the code in the question to show exactly the code you are using now. Show the exact contents of the input file. (Paste them into the question, but also use the `xxd` command to show the contents and paste its output in the question.) Show the exact output of the program. (Again, paste the output into the question, but also redirect the output to a file and use `xxd` to show the contents of that file, and paste it into the question.)
Comment: @Jabberwocky I am using cygwin gcc compiler
Comment: @ShantanuShinde oh and please let us know what you mean by _"alternate characters"_
Comment: @EricPostpischil I didn't understood what you told. Doesn't xxd create hex dump file? what should I do of it?
Comment: @ShantanuShinde we want you to show the output of `xxd`. [Edit]  your question and put all clarifications _there_.
Comment: @Jabberwocky alternate = "every other".  Hence the `lseek(fd,1,SEEK_CUR);` calls to skip a character.  Of course, there's no checking should the `lseek()` call hits EOF.
Comment: this should work with removing lseek(fd,1,SEEK_CUR); this seek is making 1 byte skip. please refer man page of read() it is clearly mentioned that if the file support seek then it will auto increment the offset to read in next call.
Comment: @Deepak I want to skip 1 character
Comment: @Shantanu Shinde: sorry for misunderstanding. this function is working fine for me. only extra i have done is as already mentioned by others open the file as:  open(argv[1], O_RDWR);
Comment: @Deepak Mine is skipping the first line as I have posted in the question.
Comment: @Shantanu Shinde: I think this seems some problem how you have saved in input file. i used gvim to copy the same line given by you above and it is printing all the line properly. by skipping properly as:
aceg
jlnp
suwy, all three and in 3 line as there is new line character
Answer: You need to #include <fcntl.h>, but that's not the actual problem.
The output
ikmoq
suwy

is actually expected.
The input file
abcdefgh
ijklmnopq
rstuvwxyz

Looks like this in memory abcdefgh\r\nijklmnopq\r\nrstuvwxyz, because under Windows line endings are represendted by "\r\n" two bytes 13 and 10.
You are printing every second character, so you print:
'a' 'c' 'e' 'g' '\r' 'i' 'k' etc.
But as you do raw output with write, the \r puts just the cursor at the beginning of the line and thus subsequent characters will overwrite the already printed characters.
Change your program like this:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char * argv[])
{
  int fd = open("input.txt", O_RDONLY);

  if (fd > 0)
  {
    char content[1];

    while (read(fd, content, 1))
    {
      if (content[0] == '\r')
      {
        static char cr[] = "<CR>";
        write(1, cr, sizeof cr - 1);
      }
      else if (content[0] == '\n')
      {
        static char lf[] = "<LF>";
        write(1, lf, sizeof lf - 1);
      }

      else
      {
        write(1, content, 1);
        lseek(fd, 1, SEEK_CUR);
      }
    }
  }
  else
  {
    printf("File could not be opened.\n");
  }

  return 0;
}

This shows what bytes are actually read from the file.
Output:
aceg<LF><CR>ikmoq<CR>rtvxz

Simplified version of the while loop using putc which deals automatically with line endings:
while (read(fd, content, 1))
{
  putc(content[0], stdout);
  lseek(fd, 1, SEEK_CUR);
}

Version using only system calls (this is probably platform dependant):
while (read(fd, content, 1))
{
  if (content[0] == '\r' || content[0] == '\n')
  {
    static char eol[] = "\r\n";
    write(1, eol, sizeof eol - 1);
  }
  else
  {
    write(1, content, 1);
  }

  lseek(fd, 1, SEEK_CUR);
}

Comment: How to avoid printing that  and  ?
Comment: @ShantanuShinde This program is for illustration purposes to show what bytes are actually read from the file. If you don't want to print out these special characters, you need to skip (ignore them). Modifying the code in the answer shouldn't be a big deal.
Comment: so if I don't write '\r\n' how do I print each line on seperate line?
Comment: @ShantanuShinde I don't have the same platform as you so I'm not sure, please show the output the code in my answer displays on your computer, then I can tell you. Otherwise don't use raw output but use functions from `` such as `putc`, `printf` etc. which will deal automatically with special characters
Comment: @ShantanuShinde I edited my answer, look at the end.
Comment: actually I have to use write, not any library functions. just system calls.
Comment: I used this: `while(read(fd,content,1))
        {
            if(content[0]!='\r')//&&content[0]!='\n')
            {
                write(1,content,1);
                lseek(fd,1,SEEK_CUR);
            }
        }` It is working now.
Comment: I think I get why \n is working but \r not. cygwin uses POSIX API, and posix has \n as newline but .txt file has \r\n as newline. I think \r\n will not work with cygwin. so please add my code for that third code block and I will select it as answer.


Looking for Linux/Windows -deployable OpenGL windowing-and-OS libraries

Question: I'd like to set up an OpenGL development environment in Linux that I can also cross-compile for Windows out of.  It looks like GLFW + OpenGL will give me what I need.
I tried installing the GLFW development package for Ubuntu 8.10, but I had dependency problems.  I may stick with it, though.
Has anyone used GLFW for Linux?  Has anyone tried cross-compiling for Windows?  Is there another solution to handle windowing with OpenGL that might be better?
Answer: I second SDL. I also suggest GLee or GLEW for extension managing as well
Answer: I would try SDL, it is very easy to use. For cross compilation, I would use MinGW or Cygwin.
Comment: Boo. SDL is simple, but slow.
Comment: @Mark: the built-in 2D drawing functions of SDL are slow, but OpenGL on SDL is not really any slower than any other library.
Answer: I would recommend looking at using Qt and OpenGL together for your windowing needs.  As of 4.5, Qt is now LGPL, and supports Linux, Windows, and Mac out of the box.
Comment: Also interesting, will look over Qt, too


Finding solutions to $x^2 \equiv -1 \pmod{701}$.

Question:
Solve the congruence
$$x^2\equiv -1 \pmod{701}$$

I have proven that $2$ is a primitive root modulo $701$ but I am not sure how to use this fact.
Comment: Well, you know the order of $2$ modulo $701$, and $x$ must be $2^k$ for some $k$. Now note that $x^4 = (x^2)^2 \equiv (-1)^2 = 1\pmod{701}$.
Comment: Hint: $701$ is a prime number. $x=135,566$ modulo $701$.
Comment: You do not need a primitive root.  You need only a nonquadratic residue.  Since $701\not\in\{1,7\}\bmod 8$, one such nonquadratic residue is $2$.
Answer: The Legendre symbol is given by
$$
\left( \frac{-1}{701}\right)=(-1)^{700/2}=1,
$$
where $p=701$ is prime. Hence there exist indeed solutions.
We have $y=2^{\frac{p-1}{2}}=2^{350} \equiv -1 \bmod 701$ so that $x^2\equiv -1\bmod 701$ for $x\equiv 2^{175}\equiv 566 \bmod 701$. So $x=566$ and $x=-566=135$ are the two solutions (modulo $701)$.
Comment: We have $2^{p-1}\equiv 1 \bmod p$ for primes $p>2$ by Fermat. Now we can try to consider a square root, i.e., $2^{\frac{p-1}{2}}$.
Comment: Can you elaborate a little more on how you got $y=2^{\frac{p-1}{2}}=2^{350} \equiv -1 \bmod 701$? Thanks!


Conjecture about Rabin-Miller pseudo prime test

Question: I tested the Rabin-Miller pseudo prime algorithm using a single test value and found that the number of false calls depends on the size of the number to test, reducing to a (conjectured) negligible probability of error for very large numbers.
A number is randomly chosen to be tested. If the number is $0,1,2,3$ or even the correct result is returned. If the number is odd and $>3$ the Rabin-Miller algorithm specified below is used. The result is compared with table values. This algorithm use a random number $a$ for the test. It would never miss a prime but occasionally report a composite to be a prime. If the test is erroneous an error is returned. I used the method at oeis A014233 where a method for exact testing of primes using multiple Rabin-Miller tests is described, together with squeezed prime tables, to assess the truth of primality.
For each $b$ I ran the test $10,000,000$ times with pseudo random numbers less than $2^b$ and then got the following number of errors $e$:
<code>  e      b    f
78144    8  78125
61425    9  55243
43642   10  39063
32688   11  27621
22201   12  19531
15190   13  13811
10789   14   9766
 7176   15   6905
 4814   16   4883
 3227   17   3453
 2122   18   2441
 1422   19   1726
  926   20   1221
  574   21    863
  400   22    610
  247   23    432
  194   24    305
  112   25    216
   65   26    153
   46   27    108
   24   28     76
   21   29     54
   11   30     38
    9   31     27
    2   32     19
    4   33     13
    4   34     10
    0   35      7
    2   36      5
    0   37      3
    0   38      2
    0   39      2
    0   40      1
    0   41      1
</code>
The f-column is the function $f(b)=1250000\cdot 2^{-\frac{b}{2}}$.
The algorithm used is:

To test an odd number $n$, write $n=2^r\cdot s+1$, where $s$ is odd.
  Given a random number $a$ such that $1<a<n$, if
  1. $a^s\equiv 1(\text{mod}\; n)$ or
  2. it exists an integer $j$: $0\le j<r$ with  $a^{2^j\cdot s}\equiv -1(\text{mod}\; n)$
then $n$ is pseudo prime.

The conjecture is:

For $b$ big enough $\text{e}<1250000\cdot 2^{-\frac{b}{2}}$.
  And specially, $\text{e}\sim 2^{-\frac{b}{2}}$.

I intend to use the algorithm for testing big integers and it seems like just one test is enough for $b>256$ since
$f(256)=\frac{1}{272225893536750770770699685945414}\,$, which is supposed to be the probability for an error within 10,000,000 random primary tests. For $b<<256$ one can use multiple tests or an exact algorithm.
But how to prove the conjecture or at least make it resonable?
I will also reward an indepentent computer test, that support or not support my own computer test.

I made a test with double check of Rabin-Miller and made a diagram:
Comment: But for every base, there are infinitely many strong (Fermat) pseudoprimes. One test is not enough to be sure you have a prime, but it makes it probable. Any fixed number of tests is not enough to be sure you have a prime.
Comment: I think part 1 of your test should read: $a^s \equiv 1 \pmod n$.
Comment: @Joffan: Thanks, you are right!
Comment: I don't understand what $e$ is. I would think that an "error" is a composite number that passes the test (for one base?). But how can you have $78144$ errors for $b = 8$, when there are only $256$ positive integers $\leqslant 2^8$?
Comment: @DanielFischer: the test repeats with different random numbers for $a$ in the algorithm. And yes, an error is when a composite flags for prime.
Comment: @Lehs how do you choose $a$? Do you only use one value of $a$?
Comment: @Joffan, no I'll try no clearify. Rectangular pseudo numbers between $1$ and $n$ are used for $a$. Each test is random based.
Comment: @DanielFischer: for small $b$ the combinations of random numbers $(n,a)$ are $<< 10,000,000$ and the same combinations occure several times.
Comment: Okay, so for small $b$, you basically check all odd numbers, and all possible bases for these numbers. Several times even, for the smallest $b$s. Thus you find all pseudoprimes and all corresponding bases [maybe not really all, but close]. For large $b$, you test only a small fraction of the odd numbers $\leqslant 2^b$, and only one base for each. For most composites $n$, the number of bases $a$ such that $n$ is a strong (Fermat) pseudoprime to base $a$ is really small. So the chance to accidentally hit one of those combinations is small.
Comment: @DanielFischer, the test runs for any number. It check 0,1,2,3 and even and then run the algorithm. The point is that the probability for a random based test to be a false prime seems to depend on the size of the number in a certain way.
Comment: Sorry, I don't understand. Can you describe more precisely what you do? You pick a $b$, and then do you create ten million pseudo-random pairs $(n,a)$ with $1 < a < n \leqslant 2^b$ to check whether $n$ is a strong base-$a$ pseudoprime, or do you create ten million $n \leqslant 2^b$ and test each $n$ with multiple bases? And what does "It check 0,1,2,3 and even" mean?
Comment: @DanielFischer: I have edited.
Comment: @Lehs I'm still not fully understanding how you pick $a$. Your text now says "a random number" but your earlier comment said "Rectangular pseudo numbers between $1$ and $n$ are used for $a$". Can you clarify? Do you mean that $a$ is chosen with equal probability from the set $\{2,3,4,…,n−1\}$?
Comment: @Joffan. Yes the last is right, as in the algorithm.
Comment: I don't think your links to that OEIS entry or (your?) blog about prime counting in Forth are sufficiently useful to give as the opening paragraph.  When you ask finally "But how to prove the conjecture or at least make it resonable?", the Reader must search back for the conjecture statement.  There one finds an inequality relating $b$ and $e$ which is not self-contained.  Your specification of "the algorithm" is welcome, but it only defines a strong primality test for *one base* $a$.  It does not correspond well to the OEIS entry (which concerns testing against mutiple bases).
Comment: @hardmath - I think I understand the author's intent and have edited to clarify. The OEIS reference had undue prominence; it's the method used to establish the truth of primality.
Comment: @Joffan: Your edits make the material flow much better.  I was making some more conservative edits (punctuation, etc.) that conflicted chronologically with yours.  At this point I'll wait to see if the OP weighs in.
Answer: The Question asks about the distribution of (odd composite) strong pseudoprimes $n$ to a base selected randomly (uniformly) from the set $\{2,\ldots,n-1\}$.
The problem has been studied in the literature.  A theoretical upper bound for the probability $p_{b}$ of a $b$-bit odd number $n\gt 1$ chosen at random (uniformly sampled) that passes the strong pseudoprime test to a random base chosen from $\{1,2,\ldots,n-1\}$ is composite is:
$$ p_b \le b^2 4^{2-\sqrt{b}} \;{ when }\; b \ge 2$$
as established by Damgård, Landrock, and Pomerance: Average Case Error Estimates for the Strong Probable Prime Test in Mathematics of Computation
Vol. 61, No. 203 (July 1993).  Note that they allow the choice of base $a=1$, for which any odd composite will pass a strong pseudoprime test, thereby increasing the chance of a false positive.
But this bound is much weaker than the empirical bounds that can be found.  For example, the above authors also report numerically that $p_{600} \le 2^{-75}$, while their theoretical bound above gives roughly $p_{600} \le 2^{-26}$.

Added:
While it is understandable that one might exclude base $a=1$ because it gives a trivial "strong-pseudoprime test" that always succeeds, the same is true of $a=n-1$.  So why not exclude that as well?
In randomly sampling the bases $a$ between $1$ and $n-1$ we introduce an element of uncertainty that complicates our analysis.  If more than one base were being used in our testing, e.g. sampling bases without replacement, an advantage would be more evident.
I'd like to support conjectured form of a chance of "error", i.e. that a number $n$ passing the Miller-Rabin (base $a$-strong pseudoprime) test yet is composite, by taking that random element out of the procedure and giving exact rather than sampled probabilities.  To this end let's settle for the sake of discussion on $a=2$ as our base.  After all, we are computing the test only for odd numbers $n$, and automatically the choice $a=2$ is coprime to $n$.
Further counting 2-strong pseudoprimes versus odd primes have been exhaustively worked out to $2^{64}$, so it makes sense to define the probability of "false success" error in a base $a=2$ test for odd numbers up to $n$ as:
$$ \frac{\text{ # of 2-strong pseudoprimes } \le n}{(\text{ # of 2-strong pseudoprimes } \le n) + (\text{ # of odd primes } \le n)} $$
The graph below is driven by data generated at increments $n = 10^k$, and then taking the negative (common) logarithm (i.e. base ten) of the probability so defined.  I find the interpretation of common logs in terms of decimal places easier to grasp, but here the key characteristic is the slope of the trend line:

Fig. 1  Graph of -log probability odd number passing 2-strong PrP is composite
This slope is roughly the one-half conjectured by OP, i.e. $e = O(2^{-b/2})$, and doesn't depend on whether base two or base ten is being used for increments.  If anything the slope seems slightly steeper than one-half, so that the chance of error is dropping a little faster.
However this doesn't convey to me that a single Miller-Rabin test is "good enough", but rather that one such test is quite efficient in weeding out composites.  A follow-on test, perhaps of an entirely different kind, is worth doing if one really wants to drive the chance of "false positive" error for primality into negligible magnitudes.
Here are the counts of $2$-strong pseudoprimes and odd primes below the indicated $10^k$ increments, summarized from the sources linked above and used to create the scatter plot and trendline with Google Sheets:
$$\begin{array}{r|r|r}
k & \text{# 2-strong pseudoprimes } \lt 10^k & \text{# of odd primes } \lt 10^k \\
\hline
4 & 5 & 1228 \\
5 & 16 & 9591 \\
6 & 46 & 78497 \\
7 & 162 & 664578 \\
8 & 488 & 5761454 \\
9 & 1282 & 50847533 \\
10 & 3291 & 455052510 \\
11 & 8607 & 4118054812 \\
12 & 22407 & 37607912017 \\
13 & 58892 & 346065536838 \\
14 & 156251 & 3204941750801 \\
15 & 419489 & 29844570422668 \\
16 & 1135860 & 279238341033924 \\
17 & 3115246 & 2623557157654232 \\
18 & 8646507 & 24739954287740859 \\
19 & 24220195 & 234057667276344606 \end{array} $$
Table 1: Counts of 2-strong pseudoprimes and odd primes up to $10^k$
Comment: I don't think the choice of $a=1 $ is allowed. I did ask about the selection range of $a$.
Comment: I will rephrase what I wrote.  I was reporting on what was done in the paper, and of course one can improve (decrease) the likelihood of a false positive if $a=1$ is excluded.
Comment: Thanks all of you! The question was a bit messy. Interesting that my experiment gives so much smaller emiprical errors than the empirical errors of the computer scientists above. My function $f$ isn´t based on anything but "looks" good.
Comment: @Joffan. I got the algorithm from http://mathworld.wolfram.com/Rabin-MillerStrongPseudoprimeTest.html but thought that the case $a=1$ was a typo, so I changed to $1<a$.
Comment: 2-strong pseudoprime means that the base $a=2$ case Miller-Rabin test succeeds for a composite, rather than for an actual prime.  So the probability of "error" is the fraction of these among all (odd number) cases where the test for base $a=2$, i.e. their count plus the number of actual (odd) primes.


Gallery related to the article

Question: I managed to create a gallery and show it under a page (creating a view of type page).
What I really need is having one different gallery associated for each article, so I created a view of type "block", but the showed gallery is always the same, while it should related to the current article.
Answer: You need to add to your view the Contextual Filter: Content: NiD
Click Provide Default Value and select Content ID from URL
Comment: Thank you, I can't check during the weekend, but I'll give a try ASAP.
Comment: I tried it, but once done I still don't understand how to create a gallery related to the specific article.
Comment: If you having trouble with this, Skip using views for adding a gallery to an article and just add the gallery directly on the article using something like http://drupal.org/project/galleryformatter and just add some image fields to the content type.

Gallery related to the article


Escaping characters in Nagios for NC_Net

Question: I'm trying to monitor an MSMQ queue counter using Nagios (3.0.1). The remote server is running NC_Net. The check_command config looks like this:
check_command check_nt!COUNTER!-l "\\MSMQ Queue(servername\\private$\\queuename)\\Messages in Queue","%.f messages in MSMQ queue" -w 5 -c 10

This doesn't work. I believe that the dollar symbol needs to be escaped and I'm having trouble working out how.
This article suggests "$$" ie.
check_command check_nt!COUNTER!-l "\\MSMQ Queue(servername\\private"$$"\\queuename)\\Messages in Queue","%.f messages in MSMQ queue" -w 5 -c 10

but that doesn't work. I've tried a few other methods (backslash, single quotes etc).
Any suggestions?
EDIT:
I've been doing some testing via the command line which is one reason I believe it's the $ causing the problem. The following works:
./check_nt -H hostip -v COUNTER -l "\\MSMQ Queue(Computer Queues)\\Messages in Queue","%.f messages in MSMQ queue" -w 5 -c 10

but this doesn't:
./check_nt -H hostip -v COUNTER -l "\\MSMQ Queue(servername\\private$\\queuename)\\Messages in Queue","%.f messages in MSMQ queue" -w 5 -c 10

I've also used ECHO to see how those commands expand but that hasn't helped me.
EDIT:
Turns out it wasn't the dollar symbol. See below.
Comment: You might want to include the service and host definitions too, that way we get the whole picture.
Comment: What is ECHO , that nagios thing?
Comment: ECHO expands the command line
Answer: You can enable full debugging in the nagios.cfg to see what the command actually expands to, this will show you if the dollar sign is actually the problem.  To do this, set the following:
debug_level=-1
debug_verbosity=2
# DEBUG FILE
debug_file=/usr/local/nagios/var/nagios.debug
max_debug_file_size=1000000

If you have a lot of checks, you need to set the max debug file size because at that verbosity and level the log fills up quick.
And them maybe (example):
sudo /etc/init.d/nagios reload

You will then need to run check, while tailing the log.  You also might want to pipe the tail to grep with something like 'check_nt' so you can lessen the noise.
Answer: I believe you need to use \ to escape the character but the following link shows you might need two \
hope this helps -> Link <-
Answer: I've discovered that NC_Net on the remote server logs to the Windows event log. Looking at the errors, I'm starting to think that it's not a problem with the dollar symbol:
I've run a couple of tests (that I expect to fail). For the first, I specified the counter name as "\MSMQ Queue(servername)\Messages in Queue"
The resulting error was:
Exeption occured during Counter check :Instance 'servername' does not exist in the specified Category.::>\MSMQ Queue(servername)\Messages in Queue

In that case, it can't find the counter instance. For the second, I specified "\MSMQ Queue(servername\test1)\Messages in Queue"
Exeption occured during Counter check :Could not locate Performance Counter with specified category name 'MSMQ Queue', counter name 'test1)\Messages in Queue'.::>\MSMQ Queue(servername\test1)\Messages in Queue

In that case, it can't find the counter.
It looks to me like NC_Net is parsing the counter names differently because of the \ in "servername\test1".
EDIT:
The problem was due to the \ in the counter instance name. I've discovered that there is an alternative syntax for specifying the counter name so the following works:
^MSMQ Queue^servername\\private\$\\queuename^Messages in Queue


Implement a vertical UIScrollView with constraints

Question: I need to put more content in the UIView but I'm not sure how to implement a UIScrollView to put much more content, and this only scrolls horizontally.
import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    /*DECLARACION DE OBJETOS*/

    //Declaracion del Label
    let Titulo = UILabel() as UILabel;
    let Titulo_Clima = UILabel() as UILabel;
    let Texto = UILabel() as UILabel;

    let texto_Titulo = "Hola.";
    let texto_Inicio = "Bienvenidos a Robinsonia, esta aplicacón te ayudará a organizar tu viaje a Robinson Crusoe, selecciona las opciones en el menu principal, haciendo clic en el boton superior izquierdo.";

    let texto_Clima = "Clima";

    /*FIN DECLARACION DE OBJETOS*/

    //FUNCION PARA PERMITIR COLORES HEXÁDECIMALES
    func uicolorFromHex(rgbValue:UInt32)->UIColor{
        let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0;
        let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0;
        let blue = CGFloat(rgbValue & 0xFF)/256.0;

        return UIColor(red:red, green:green, blue:blue, alpha:1.0);
    }
    //***

    override func viewDidLoad() {
        super.viewDidLoad()

         //ITEM QUE ABRE EL MENU.
        title = "Crusoe";
        view.backgroundColor = uicolorFromHex(0xD9E5EA);

        //Imagen icono menu principal
        let b3 = UIBarButtonItem(image:UIImage(named:"Menu"), style:.Plain, target:self, action:"presentLeftMenuViewController");
        navigationItem.leftBarButtonItem = b3;

        //Color de Fuente
        let fuente_titulo = UIFont (name: "Oxygen", size: 35);
        let fuente_tituloClima = UIFont (name: "Oxygen", size: 26);
        let fuente_texto = UIFont (name: "Oxygen", size: 17);
        let color_fuente_texo = uicolorFromHex(0x484A4B);
        let color_fuente_titulos = uicolorFromHex(0x3A3B3C);

        //**** Logica de contenido
        let button = UIButton.buttonWithType(UIButtonType.System) as! UIButton;
        button.frame = CGRectMake(10, 10, 200, 100);
        button.backgroundColor = UIColor.greenColor();
        button.setTitle("Test Button", forState: UIControlState.Normal);
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside);

        //Dibujo el Label.
        Titulo.text = texto_Titulo;
        Titulo.font = fuente_titulo
        Titulo.textAlignment = .Center;
        Titulo.textColor = color_fuente_titulos;
        Titulo.setTranslatesAutoresizingMaskIntoConstraints(false);

        //Dibujo el titulo del clima
        Titulo_Clima.text = texto_Clima;
        Titulo_Clima.font = fuente_tituloClima;
        Titulo_Clima.textAlignment = .Left;
        Titulo_Clima.textColor = color_fuente_titulos;
        Titulo_Clima.setTranslatesAutoresizingMaskIntoConstraints(false);

        //Dibujo texto de inicio.
        Texto.text = texto_Inicio;
        Texto.font = fuente_texto;
        Texto.textAlignment = .Center;
        Texto.textColor = color_fuente_texo;
        Texto.numberOfLines=6;
        Texto.setTranslatesAutoresizingMaskIntoConstraints(false);

        //*** DEFINIENDO EL COLOR DEL BORDER
        let borderColor : UIColor = uicolorFromHex(0xFFFFFF);

        //*** VIEW SUPERIOR
        var topView = UIView();
        topView.setTranslatesAutoresizingMaskIntoConstraints(false);

        //*** VIEW UNO
        var bottomView = UIView();
        //bottomView.backgroundColor = UIColor(white: 1, alpha: 0.1);
        bottomView.setTranslatesAutoresizingMaskIntoConstraints(false);

        //*** VIEW DOS
        var bottomView_dos = UIView();
        bottomView_dos.backgroundColor = UIColor(white: 1, alpha: 0.1);
        bottomView_dos.setTranslatesAutoresizingMaskIntoConstraints(false);

        //*** DEFNIENDO LOS OBJETOS CON 0 OPACIDAD
        Titulo.alpha = 0;
        Texto.alpha = 0;
        bottomView.alpha = 0;
        bottomView_dos.alpha = 0;

        //*** INICIALIZANDO LOS VIEWS
        self.view.addSubview(topView);
        self.view.addSubview(bottomView);
        self.view.addSubview(bottomView_dos);

        //*** TEXTOS
        topView.addSubview(Titulo); // titulo del inicio
        topView.addSubview(Texto); // texto del inicio
        bottomView.addSubview(Titulo_Clima); // titulo del clima

        //*** DEFINIENDO LAS ANIMACIONES PARA LOS OBJETOS
        UIView.animateWithDuration(1.0, animations: {
            self.Titulo.alpha = 1.0
            bottomView.alpha = 2.0
            bottomView_dos.alpha = 3.0
        })

        UIView.animateWithDuration(1.5, animations: {
            self.Texto.alpha = 1.0
        })

        //*** DICCIONARIO
        let viewsDictionary = ["top":topView
                                ,"bottom":bottomView
                                ,"bottom_dos":bottomView_dos
                                ,"button":button
                                ,"Titulo":Titulo
                                ,"Texto":Texto
                                ,"Titulo_Clima":Titulo_Clima]

        //*** POSICION DE LOS VIEWS HORIZONTAL
        let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[top]-10-|",
                                                                                options: NSLayoutFormatOptions(0),
                                                                                metrics: nil,
                                                                                views: viewsDictionary)
        let view_constraint_H2:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[bottom(bottom_dos)]-[bottom_dos]-10-|",
                                                                                options: NSLayoutFormatOptions(0),
                                                                                metrics: nil,
                                                                                views: viewsDictionary)

            view.addConstraints(view_constraint_H as [AnyObject])
            view.addConstraints(view_constraint_H2 as [AnyObject])

        //*** POSICION DE LOS VIEWS VERTICAL
        let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-65-[top(bottom)]-[bottom]-10-|",
                                                                                options: NSLayoutFormatOptions.AlignAllLeading,
                                                                                metrics: nil,
                                                                                views: viewsDictionary)
        let view_constraint_VV:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-65-[top(bottom_dos)]-[bottom_dos]-10-|",
                                                                                options: NSLayoutFormatOptions(0),
                                                                                metrics: nil,
                                                                                views: viewsDictionary)

            view.addConstraints(view_constraint_V as [AnyObject])
            view.addConstraints(view_constraint_VV as [AnyObject])

        //*** POSICION DEL TITULO
        let view_constraint_H_Titulo:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[Titulo]-0-|",
                                                                                options: NSLayoutFormatOptions.AlignAllLeading,
                                                                                metrics: nil,
                                                                                views: viewsDictionary)

        let view_constraint_V_Titulo:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[Titulo]-[Texto]",
                                                                                options: NSLayoutFormatOptions.AlignAllLeading,
                                                                                metrics: nil,
                                                                                views: viewsDictionary)

            topView.addConstraints(view_constraint_H_Titulo as [AnyObject])
            topView.addConstraints(view_constraint_V_Titulo as [AnyObject])

        //*** POSICION DEL TITULO PARA EL CLIMA
        let view_constraintTituloClima_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[Titulo_Clima]-5-|",
                                                                                options: NSLayoutFormatOptions.AlignAllLeading,
                                                                                metrics: nil,
                                                                                views: viewsDictionary)

        let view_constraintTituloClima_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[Titulo_Clima]",
            options: NSLayoutFormatOptions.AlignAllLeading,
            metrics: nil,
            views: viewsDictionary)

        bottomView.addConstraints(view_constraintTituloClima_H as [AnyObject])
        bottomView.addConstraints(view_constraintTituloClima_V as [AnyObject])

        //*** POSICION DEL TEXTO
        let view_constraint_H_Texto:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[Texto]-0-|",
                                                                                options: NSLayoutFormatOptions.AlignAllLeading,
                                                                                metrics: nil,
                                                                                views: viewsDictionary)

            topView.addConstraints(view_constraint_H_Texto as [AnyObject])

        //***

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*Funciones Extras*/
    func buttonAction(sender:UIButton!)
    {
        println("Button tapped")
    }

}

Answer: The key to creating constraints with a scroll view's subviews is that the constraints are used to dictate the size of the contentSize of the scroll view. (Usually constraints dictate the frame of subviews, but with scroll view's it goes the other way around, controlling the contentSize that dictates the scrolling behavior.) Thus, if you want labels to not exceed the width of the screen, you don't want to just add constraints between the labels and the scroll view, but also to the scroll view's superview, too.
One way to do that is to not put the views directly in the scroll view, but rather put a "container view" (actually just a simple UIView, but we often call it a "container" because it does nothing but contains other view objects) inside the scroll view and then add the labels to the container view. So, if you had a scroll view with nine labels vertically laid out, you would end up with a view hierarchy that looks like so:
<view: 0x7fdb58b123e0; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x7fdb58b079c0>>
   | <scrollView: 0x7fdb59012600; frame = (0 0; 375 667); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7fdb58810ba0>; layer = <CALayer: 0x7fdb5880bc80>; contentOffset: {0, 0}; contentSize: {375, 1907}>
   |    | <contentView: 0x7fdb58813fd0; frame = (0 0; 375 1907); layer = <CALayer: 0x7fdb58814130>>
   |    |    | <label1: 0x7fdb588143a0; frame = (8 8; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb588149d0>>
   |    |    | <label2: 0x7fdb58816980; frame = (8 219; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb58816b80>>
   |    |    | <label3: 0x7fdb58817110; frame = (8 430; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb58817310>>
   |    |    | <label4: 0x7fdb58817830; frame = (8 641; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb58817a30>>
   |    |    | <label5: 0x7fdb58817e00; frame = (8 852; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb58804c10>>
   |    |    | <label6: 0x7fdb588183f0; frame = (8 1063; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb588185f0>>
   |    |    | <label7: 0x7fdb588189f0; frame = (8 1274; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb58818bf0>>
   |    |    | <label8: 0x7fdb588190a0; frame = (8 1485; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb588192a0>>
   |    |    | <label9: 0x7fdb588196a0; frame = (8 1696; 359 203); text = 'Lorem ipsum dolor sit ame...'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fdb588198a0>>

To get this laid out correctly, there are three sets of constraints to add:

Layout the scroll view with respect to its superview (in this case, the view controller's root view):
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: [], metrics: nil, views: views))

Next, layout the content view with respect to scroll view's contentSize:
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView]|", options: [], metrics: nil, views: views))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: [], metrics: nil, views: views))

Specify that the contentView should be the same width as the scroll view's superview (view):
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[contentView(==view)]", options: [], metrics: nil, views: views))

Note, although the contentView is subview the scrollView, this constraint is added to the scroll view's superview, because this constraint refers to that superview's width.
Also note that if you want, you can actually combine this constraint with the horizontal constraint listed in point 2, above, but I've separated it here to try to make it as clear as possible.
Finally, now define the labels' constraints with respect to the content view:
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label1]-[label2]-[label3]-[label4]-[label5]-[label6]-[label7]-[label8]-[label9]-|", options: [], metrics: nil, views: views))

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label1]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label2]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label3]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label4]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label5]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label6]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label7]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label8]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label9]-|", options: [], metrics: nil, views: views))

Note, that vertical constraint defines not only the distance from the first label and the top of the content view, but also the distance from the last label to the bottom of the content view.

But the key point here is the combination of point 2 (which says "make the contentSize of the scroll view the size of this new 'content view'") and point 3 (which says "but make the 'content view' no wider than the screen). If you don't do both of those steps, you won't get the vertical scrolling that you appear to be looking for.
Also note that if you want label to resize automatically for you, you can set numberOfLines to zero, and the label's intrinsic size will change to fit the text.
Clearly, your view hierarchy isn't quite like this (you have the two bottom views and the like), but I'm illustrating the basic concept of how to get scroll view's to layout correctly with auto layout constraints.


Bad Request Error while sending sendgrid email using wadeshuler/yii2-sendgrid

Question: I am currently working on a yii2 application and I have integrated wadeshuler/yii2-sendgrid plugin in my application to send emails through it.
I have setup a dynamic template with a template id in my sendgrid account. Here is the code I am using to test sendgrid integration with my app.
public function actionTest()
{
    $mailer = Yii::$app->mailer;
    $message = $mailer->compose()
        ->setTo('umair@****.com')      // or just $user->email
        ->setFrom(['firstname.lastname@example.com' => 'Alerts'])
        ->setReplyTo('email@example.com')
        ->setSubject('Hey -username-, Read This Email')
        ->setHtmlBody('Dear -username-,

My HTML message here')
        ->setTextBody('Dear -username-,\n\nMy Text message here')
        ->setTemplateId('******')

        ->addSubstitution('-username-', 'Umair Ashraf')
        ->send();

    if ($message === true) {
        echo 'Success!';
        echo '
' . print_r($mailer->getRawResponses(), true) . '
';
    } else {
        echo 'Error!
';
        echo '
' . print_r($mailer, true) . '
';
        echo '
' . print_r($mailer->getErrors(), true) . '
';
    }

}

Here is the response code printed

Error!
  {"code":400,"headers":["HTTP/1.1 400 Bad Request","Server: nginx","Date: Fri, 27 Dec 2019 13:31:27 GMT","Content-Type: application/json","Content-Length: 238","Connection: keep-alive","Access-Control-Allow-Origin: https://sendgrid.api-docs.io","Access-Control-Allow-Methods: POST","Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl","Access-Control-Max-Age: 600","X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html","",""],"body":"{\"errors\":[{\"message\":\"Substitutions may not be used with dynamic templating\",\"field\":\"personalizations.0.substitutions\",\"help\":\"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions\"}]}"}
Array
   (
      [0] => Bad Request!
   )

As you can see it says that substitutions may not be used with dynamic templating, but I will be needing to substitute these variable inorder to use templates correclty. How to fix this using the code?
Comment: Read this [issue](https://github.com/sendgrid/sendgrid-php/issues/659) to get the details for fixing this error
Answer: I had to remove wadeshuler/yii2-sendgrid plugin as it didn't support the latest features and updates in the sendgrid liberary. I installed the latest sendgrid plugin. I also made a component named SendGridManager to route all the emails through it in my application.
Here is my function inside the component SendgridManager
public function email($from , $to, $substitution, $templateId, $senderName = NULL,
$toName = NULL, $attachment = NULL)
{
    $response = '';
    $email = new \SendGrid\Mail\Mail();
    $email->setFrom($from,$senderName);
    $email->addTo($to , $toName, $substitution);
    $email->setTemplateId($templateId);
    if(!empty($attachment))
    {
        $email->addAttachment(
            $attachment
        );
    }
    $sendgrid = new \SendGrid($this->apiKey);

    try {
        $response = $sendgrid->send($email);

    } catch (Exception $e) {
        echo 'Caught exception: '.  $e->getMessage(). "\n";
    }

    return $response;
}


How to get following output in c#?

Question: Create a function which will take two parameter as integer, and will return output like this -:
xxxxxx
xoooox
xoxxox
xoooox
xxxxxx
example-:
i have a function in which i am passing two parameter like (5,6), now first parameter 5 will means 5 rows and 6 means 6 column and it should return array or something with the following output, don't forget that parameter value can be change so output should be according to the parameter but in the same format. How to do this?
Comment: someone asked me this question, and i don't know how to do this.
Comment: @AnilThakur The Question is not clear and the title doesn't reflect the actual problem, we are more than happy to help you but not solve the quiz on behalf of you
Answer: I believe it is something like this:
<code>    public IEnumerable<string> foo(int lines, int columns) {
        List<string> ret = new List<string>(lines);

        for (int l = 1; l <= lines; l++) ret.Add(new String('x', columns));

        return ret;
    }
</code>

How to get following output in c#?


Book Recommendation for Mathematical Statistics

Question: Hi I am first year undergrad with math background, next year I will be starting a course in introductory mathematical statistics at the University of Toronto,
and the textbook the university uses, Mathematical Statistics and Data Analysis by Rice, has received very poor ratings both from past students and online. So I was hoping if someone can give me a list of books that I can use instead? (And also hopefully cover the sequel to the course as well.)
Here's a copy of the syllabus (pdf).
Right now I have found two books that may help:

Statistical Inference, by Casella
Problems in Probability Theory Mathematical Statistics and Theory of Random Functions
Answer: I personally recommend "Mathematical Statistics" by Terrell,
which, I think, is not well-known.
http://www.amazon.com/Mathematical-Statistics-Unified-Introduction-Springer/dp/0387986219/ref=sr_1_1?ie=UTF8&qid=1366293457&sr=8-1&keywords=mathematical+statistics+terrell
It's very concise(it might be too concise to understand it easily)
and covers almost everything, but not deeply.


Build do Sublime Text 2 dá resultado diferente do iPython na linha de comando

Question: Estou tentando migrar para o Sublime Text 2 e fazer tudo sem sair do programa. Antes eu rodava um script com a seguinte linha:
from scipy.stats import beta, bernoulli, gaussian_kde

No shell dentro do iPithon o comando roda normalmente.
Já se eu der o build (cmd+b ou Tools -> Build)  dentro do Sublime Text 2 ele não encontra o scipy.stats e retorna o seguinte erro:

ImportError: No module named scipy.stats

Como resolver isso?
Answer: Provavelmente o Sublime Text está usando outra instalação do Python (que não tem instalada a biblioteca Scipy).
Para usar a versão correta do Python, é necessário modificar uma configuração no arquivo Python.sublime-build, que fica em em Preferences > Browse Packages » Python. A configuração correta depende do seu sistema, suas configurações, e suas preferências pessoais:
Opção 1: Alterar o caminho da instalação do Python
Defina o caminho da sua instalação do Python manualmente dentro da opção "cmd":
"cmd": ["C:/caminho/do/python/python.exe", "-u", "$file"],

Opção 2: Especificar o PATH
Copie o conteúdo da sua variável PATH para a opção "path":
"path": "C:\\caminho\\do\\python;C:\\caminho\\de\\outra\\coisa",

Opção 3: Especificar o PYTHONPATH
Especifique o caminho do PYTHONPATH desejado em uma entrada do dicionário "env":
"env": {
    "PYTHONPATH":"C:/caminho/do/python;C:/caminho/do/python/2.7.2/lib/python2.7/site-packages"
},

Comment: Ok! Vou dar uma organizada na resposta para contemplar todas as possíveis soluções. Também uso Mac, mas como somos minoria, deixei a resposta no padrão Windows, haha..
Comment: Realmente, parece que o sublime já vem com um Python em vez de buscar a versão mais recente. Eu estou usando mac, então fiz uma modificação diferente da sugerida por você, mas valeu pela resposta! Primeiro peguei o `path` no shell com o comando `env`, depois colei o path no arquivo `python.sublime-build` com `"path": "caminho do env",`.


Como checar se há algum string repetido em uma lista?

Question: Gostaria de aprender uma maneira mais fácil de checar todos items em uma lista
e procurar por strings repetidos.
Atualmente estou fazendo desta forma:
elif "azul" in fios[0] and fios[1] or "azul" in fios[1] and fios[2] or "azul" in fios[0] and fios[2]:
    print("Corte o último fio azul")

Minha intenção é checar se há mais de um "azul" dentro da lista fios,
o código está funcionando, mas gostaria de torná-lo mais pratico.
Answer: Basta você utilizar o método count do objeto list:
cores = ['azul', 'amarelo', 'vermelho', 'preto']

print(cores.count('azul'))  # 1

cores = ['azul', 'amarelo', 'vermelho', 'azul']

print(cores.count('azul'))  # 2

Comment: elif fios.count("azul") is >= 2:               ficou certo?
Comment: Não tem o operador `is`, apenas o `>=`


Does MAPLE not simplify correctly or am I goofing?

Question: While attempting to answer
this question
with help of MAPLE, something very strange happened, at least according to me. We have the following function:
$$
\phi(x,y) = x^2-y^2+\frac{x^2-y^2}{(x^2+y^2)^2}
$$
The partial derivatives of this function are (according to MAPLE and myself):
$$
u = \frac{\partial \phi}{\partial x} = 2 x + \frac{2 x}{(x^2+y^2)^2} - \frac{4(x^2-y^2)x}{(x^2+y^2)^3} \\
v = \frac{\partial \phi}{\partial y} = - 2 y - \frac{2 y}{(x^2+y^2)^2} - \frac{4(x^2-y^2)y}{(x^2+y^2)^3}
$$
Then we calculate $\sqrt{u^2+v^2}$ and ask MAPLE to simplify, with the following result:
$$
\sqrt{u^2+v^2} = 2\,\sqrt {{\frac{x^8+4\,x^6y^2-2\,x^4+6\,x^4y^4
+12\,x^2y^2+4\,x^2y^6-2\,y^4+y^8 \color{red}{+1}}{\left(x^2+y^2\right)^{3}}}}
$$
But, even at first sight .. how can there be a $+1$ in that fraction ? Here comes the MAPLE sequence:

phi(x,y) := (x^2-y^2)+(x^2-y^2)/(x^2+y^2)^2;
diff(phi(x,y),x); diff(phi(x,y),y);
simplify(sqrt(diff(phi(x,y),x)^2+diff(phi(x,y),y)^2));

I use a legal MAPLE 8 version, to be precise.
Comment: Why wouldn't there be a constant term in the numerator?  Let $y=0$.  Then $v=0$ and $u^2=4(x^4-1)^2/x^6$ so there *must* be a constant term.
Answer: Nothing wrong here, for example if you set $y=0$ and simplify by hand, you get
$$\sqrt{u^2} = 2\sqrt{\frac{(x^4-1)^2}{x^6}}$$
exactly what Maple says. You can see how $1$ emerges...
Comment: Ah, now I see: there is no $(x^2+y^2)^6$ but an $(x^2+y^2)^3$ in that denominator under the square root. My bad.
Answer: Maple 18 gives the same answer, which, as far as I can tell, is correct.
 For example, at $x=3, y=7$ both $\sqrt{u^2+v^2}$ calculated directly and Maple's answer simplify to $15\sqrt{50297} \sqrt{58}/1682$.
Answer: Here is a link for Maple bugs:
http://www.math.ncsu.edu/MapleInfo/MapleArchive/BugList.html
This is for maple V, but it was only a quick search. The moral of the story is be careful, and don't be so quick to discount drawnonward. I have had problems with Maple before....years ago. And I have a great memory. Oh, and I think all those down votes we certainly a bit hasty, as was my original answer. I apologize.
Comment: No hard feelings and (+1) for this answer. OK?
Comment: Non at all...ty. The fact of the matter is that algorithms are used to do these calculations, so anyone that thinks they are perfect is way off. Calculators use mac series to calculate trig. functions, and at the risk of getting down voted again, I have had calculation errors there as well....technology isn't perfect, and you weren't wrong to ask if it was an error.
Comment: As for the others that down voted me, they are forgiven too. I was being argumentative. Although @user61527 clearly you are the one who is "pretty much wrong"