What will be the maximum value of expression: 7sin²x + 5cos²x +√2[sin(x/2) + cos(x/2)]?

Question: This is what I've managed to do:
$=5 + 2\sin²x +√2[\sin(x/2) + \sin(π/2 - x/2)]$
$=5 + 2\sin²x + √2[2.\sin((x/2 + π/2 -x/2)/2)·\cos((x/2 - π/2 + x/2)/2)]$
$=5 + 2\sin²x + √2[2\sin(π/4)\cos(x/2 - π/4)]$
$=5 + 2\sin²x + 2\cos(x/2 - π/4)$
From here I've tried to reduce everything to $\sin(x/2)$ and $\cos(x/2)$ but unfortunately I can't do anything further.
Please help and provide a solution.
Comment: Please use [MathJax](https://math.meta.stackexchange.com/q/5020/876009)
Answer: $f(x) = 5 + 2\sin^2(x) + \sqrt{2}(\sin(x/2) + \cos(x/2))$
Let $u = \sin(x/2) + \cos(x/2)$, so $u^2 = 1 + 2 \sin(x/2) \cos(x/2)$.
Also, $\sin(x) = 2 \sin(x/2) \cos(x/2) = u^2-1$.
Substituting back: $f(u) = 5 + 2(u^2-1)^2 + \sqrt{2}u$.
Now we are in the polynomial world. Follow the usual steps to find extrema? (keep in mind that by defintion $u \in [-\sqrt{2}, \sqrt{2}]$.)
Comment: Thank you very much, I would never think of such an easy solution. Cheers!
Answer: HINT
I would start with noticing that
\begin{align*}
\sqrt{2}\left[\sin\left(\frac{x}{2}\right) + \cos\left(\frac{x}
{2}\right)\right] & = 2\times \left[\frac{1}{\sqrt{2}}\times\sin\left(\frac{x}{2}\right) + \frac{1}{\sqrt{2}}\times\cos\left(\frac{x}{2}\right)\right]\\\\
& = 2\sin\left(\frac{x}{2} + \frac{\pi}{4}\right)
\end{align*}
Moreover, we do also have that
\begin{align*}
7\sin^{2}(x) + 5\cos^{2}(x) & = 7\times [\sin^{2}(x) + \cos^{2}(x)] - 2\cos^{2}(x)\\\\
& = 7 - 2\cos^{2}(x)\\\\
& = 6 - \cos(2x)
\end{align*}
Hence the proposed function can be described as
\begin{align*}
f(x) & := 7\sin^{2}(x) + 5\cos^{2}(x) + \sqrt{2}\times\left[\sin\left(\frac{x}{2}\right) + \cos\left(\frac{x}{2}\right)\right]\\\\
& = 6 - 2\cos(2x) + 2\sin\left(\frac{x}{2} + \frac{\pi}{4}\right)
\end{align*}
whose first derivative is given by:
\begin{align*}
f'(x) = -4\sin(2x) + \cos\left(\frac{x}{2} + \frac{\pi}{4}\right)
\end{align*}
Can you take it from here?


Find $t\in \Bbb R$ such that $3$ vectors are non coplanar

Question: For which $t\in \Bbb R$ are vectors $\vec{a}=\vec{i}+2\vec{j}+3\vec{k}$ , $\vec{b}=\vec{i}+t\vec{j}+\vec{k}$ and $\vec{c}=\vec{i}+\vec{j}+\vec{k}$ non coplanar?
Vectors are non coplanar if and only if $\alpha\vec{a}+\beta\vec{b}+\gamma\vec{c}=0 \iff \alpha=\beta=\gamma=0$
So in this case $\alpha(\vec{i}+2\vec{j}+3\vec{k})+\beta(\vec{i}+t\vec{j}+\vec{k})+\gamma(\vec{i}+\vec{j}+\vec{k})=0 \iff \alpha=\beta=\gamma=0$
$\alpha\vec{i}+2\alpha\vec{j}+3\alpha{k}+\beta\vec{i}+\beta t\vec{j}+\beta\vec{k}+\gamma\vec{i}+\gamma\vec{j}+\gamma\vec{k}=0$
I know I should do this, but I don't understand why I'm doing it:
$(\alpha+\beta+\gamma)\vec{i}+(2\alpha+t\beta+\gamma)\vec{j}+(3\alpha+\beta+\gamma)\vec{k}=0$
$\alpha+\beta+\gamma=0$
$2\alpha+t\beta+\gamma=0$
$3\alpha+\beta+\gamma=0$
What are we trying to accomplish here? And how do I solve this system?
Comment: Do you know determinants?
Comment: @Bernard No, we haven't done matrices yet.
Answer: From the first equation and the third equation it is obtained that $\alpha$ is $0$. Then, we also obtain that $\beta=-\gamma$. So, the middle equation helps us to find out $t$.
$0+t\cdot \beta + \gamma=0$, $t \cdot \beta - \beta=0$, $\beta(t-1)=0$. So, $\beta=0$ or $t=1$.
Comment: yes, of course :)
Comment: Actually shouldn't the answer be $t \ne 1$ since we want them to be non coplanar. So t not 1 forces all the coefficients to zero which is what we want for the non coplanar case.
Answer: For this system not to have trivial solution only (0,0,0), determinant of the matrix has to be 0
$$αtβγ+3αβγ+2αβγ-αβγ-2αβγ-3αtβγ=0 / :αβγ$$
$$-2t+2=0 $$
$$t=1$$
Comment: Yes, so for the trivial solution, which is the non coplanar case, $t \ne 1$
Comment: Ah yes, it was asked when they are not coplanar, so when t≠1


Android FOCUS_MODE_CONTINUOUS_VIDEO and capturing preview frames

Question: I'm developing an image recognition app and would like the camera to focus automatically all the time. The folks at ZXing have solved this problem by calling autofocus() every few seconds, but on some cameras this doesn't focus smoothly, but zips to one end and refocuses. On my Alcatel 995, gingerbread 2.3.3 API level 10 phone, it actually makes an alarming click every time this happens.
This phone doesn't support FOCUS_MODE_CONTINUOUS_PICTURE. I tried using FOCUS_MODE_CONTINUOUS_VIDEO, which is supported, and it didn't work. I wrote a test app that captured every preview frame of the camera normally with a callback, but it didn't focus. I added a video recorder feature to the app, and when video is being recorded, the camera does autofocus all the time. But video recording takes away the ability to get a callback on each frame, I think. It's been discussed at
https://stackoverflow.com/questions/9477042/extract-video-frames-while-recording-the-video-on-android?rq=1
and
How to show real time filtered camera preview while recording videos?
Here is some of that test code:
public void surfaceCreated(SurfaceHolder holder) {
    mCamera = Camera.open();
    try {
        Camera.Parameters parameters = mCamera.getParameters();
        mCamera.setDisplayOrientation(90); // just get it right for testing
        mCamera.setParameters(parameters);
        mCamera.setPreviewDisplay(holder);
        mCamera.setPreviewCallback(new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera arg1) {
                Log.d(TAG, String.format("Frame %d", mFrameNumber++)); // see the frames in the logcat
            }
        });
    } catch (IOException exception) {
        mCamera.release();
        mCamera = null;
        Log.d(TAG, "exception setting parameters");
    }
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
    Camera.Parameters parameters = mCamera.getParameters();
    List<Size> previewSizes = parameters.getSupportedPreviewSizes();
    Size previewSize = getOptimalPreviewSize(previewSizes, w, h);
    parameters.setPreviewSize(previewSize.width, previewSize.height);
    parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
    mCamera.setParameters(parameters);
    mCamera.startPreview();
    if (mRecordingVideo)
        startVideo(mCamera, holder);
}

// derived from http://developer.android.com/guide/topics/media/camera.html#capture-video
private void startVideo(Camera camera, SurfaceHolder holder) {
    camera.stopPreview(); // not specified in documentation but seems to be needed
    camera.unlock();
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setCamera(camera);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // No audio is recorded
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
    mMediaRecorder.setOutputFile("/dev/null");
    try {
        mMediaRecorder.setPreviewDisplay(holder.getSurface());
        mMediaRecorder.prepare();
    } catch (IOException e) {
        camera.release();
        Log.d(TAG, "startVideo: Failed.");
        e.printStackTrace();
    }
    mMediaRecorder.start();
}

If I set mRecordingVideo in the above code to start the video recorder, I gain autofocus but lose the per-preview-frame callbacks.
The Camera.Parameters class definition says that FOCUS_MODE_CONTINUOUS_VIDEO is "intended for video recording" but doesn't make plain that it doesn't work otherwise.

Is there anything else I can do to persuade continuous autofocus to work in a gingerbread phone without recording video? Have I missed something out?
Is this phone-specific? Do other phones continuous autofocus in this mode without recording video? I posted the source of a complete test app to Github if anyone would like to try it on their phone.
Comment: Image recognition on phones in 2012, you must be a pioneer. Would you like to shed more light on what you intended to do and how the tech has improved these days that it is very easy to do similar stuff?
Comment: Grief, was it that long ago? It wasn't really image recognition, it read various barcodes and Digimarc watermarks. It definitely was made harder because all the phones had very idiosyncratic implementations of various APIs back then. Much more coherent nowadays. But we did manage to get it all working in the end.
Answer: Someone kindly helped me out by testing this on another phone on another continent. Thanks very much, Colin!

It appears that the code above is correct and should cause the camera to focus properly.
This behaviour is phone-specific. The Alcatel 995 running 2.3.6 definitely does not focus in this mode without the video recorder running. A Samsung Galaxy Nexus (not sure which OS) running the same code does focus without the video recorder running.
Answer: try "setRecordingHint(true)" to the camera parameters
Comment: You may well be right, but all the phones that I'm using for testing right now work fine without that, so I cannot tell. Phone camera operation has improved greatly in the last 3 years. Thanks, anyway!
Comment: I got a similar problem still today with Nexus 5, SGS 6 etc... when I just set CONTINUOUS_VIDEO to the camera, it doesnt work... instead it uses CONTINUOUS_PICTURE. Only when I call setRecordingHint(true) too, the focus really uses CONTINUOUS_VIDEO.
Comment: The code I'm using now prefers continuous_picture over continuous_video, so I don't see the problem on a nexus 5. But thanks for the (literal) hint!


Formula to recalculate variables from real numbers range to non-negative range

Question: I'm struggling with this for quite some time now. I'm trying to recalculate values uniformly distributed in real numbers range to numbers in non-negative range. Length of non-negative range can vary (but always is a power of two), and with increasing the length, amount of numbers increases up to length of second range, and step decreases.
Example 1:
The fixed real range is (-16,16). The non-negative range is <0,32). Amount of numbers is 32. Step is equal 0.5.
Now we want to recalculate numbers so that the first number in first range will be equal to first range in second range, i.e.:
-15.5 = 0,
-15 = 1,
15.5 = 31.
Example 2:
The fixed real range is (-16,16). The non-negative range is <0,64). Amount of numbers is 64. Step is equal 0.25.
Now:
-15.75 = 0,
15.75 = 31.
Probably it's just a simple task, but I'm after many hours of hardcore programming and samehow cannot come up with a proper solution.
Answer: The number of steps in your range is $\dfrac{2\max }{\text{step}}-1$, (where $\max$ is the end of the interval, but that value is not used) so in your first case there are $\dfrac{2\times 16}{0.5}-1=63$  If you want to map them into $[0,32)$ the stepsize has to be $0.5$.  As the step sizes are the same, the mapping is just $\text{new}=\text{old}+15.5$.  For your second case, there are $\dfrac{2\times 16}{0.25}-1=127$ steps.  To fit them into $[0,64)$ you need a step of $0.5$  As the step size doubles, the mapping is $\text{new}=2(\text{old}+15.75)$  In the general case the procedure would be:
1) calculate the number of steps as $\dfrac{2\max}{\text{step}}-1$
2) calculate the minimum old value as $\min + \text{step}$
3) calculate the new step size = $(\text{old step}) \dfrac{\text{new range}}{\text{old range}}$
4) as you want the minimum new value to be zero (is this always true?), you have $\text{new value}=\dfrac{\text{new step}}{\text{old step}}(\text{old value}-\text{minimum old value})$
Comment: yes, the minimum value is always 0
Comment: Shouldn't you add one instead of subtract one to find the number of steps? For example, from -1 to 1 in steps of 1 is 3 possibilities, but your formula only yields 1. Or are you assuming that the OP means to exclude the endpoints?
Comment: @HenningMakholm:I subtracted $1$ because I used the end of the interval (16) instead of the end step (15.5).  Yes, from the examples I took OP to be excluding the endpoints.  I will make that clear.
Comment: Ah, I must be blind.
Comment: the ranges look just as Ross said. First is opened both sides, second is closed from the zero side.


How to calculate this $\sin\frac{\pi}{9}\sin\frac{2\pi}{9}\sin\frac{4\pi}{9}$?

Question: I'm stuck with the expression
$$\sin\frac{\pi}{9}\sin\frac{2\pi}{9}\sin\frac{4\pi}{9}.$$
I have no idea how to begin, please give me a hint!
(The answer should be $\sqrt3/8$.)
Comment: hint: what is
$$\sin\frac{\pi}{9}\sin\frac{2\pi}{9}\sin\frac{3\pi}{9}\sin\frac{4\pi}{9}\sin\frac{5\pi}{9}\sin\frac{6\pi}{9}\sin\frac{7\pi}{9}\sin\frac{8\pi}{9}$$

Noting that $\sin\dfrac{3\pi}{9}=\sin\dfrac{\pi}{3}$ is known, and
$\sin x = \sin (\pi-x)$
Answer: Remember that the polynomial $P(x)=3x-4x^3$ has the property $P(\sin t)=\sin 3t$. Therefore $x_1=\sin \pi/9$,
$x_2=\sin 2\pi/9$ and $x_3=-\sin4\pi/9$ are all solutions of the equation
$P(x_i)=\sin \pi/3=\sqrt3/2$. In other words they are zeros of $P(x)-\sqrt3/2$. The leading coefficient of $P$ is $-4$, so
$$
-4x^3+3x-\sqrt3/2=P(x)-\sqrt3/2=-4(x-x_1)(x-x_2)(x-x_3).
$$
Expand the product on the right hand side, and compare the constant terms.


Cant submit form

Question: Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did.
<input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if ($row["star"] =="5") echo "checked";?> value="5"/>

a querystring is required for the form so I'm using a form action like this
<form name="submit" action="http://example.com/page.php?id=<?php echo $urlid;?>&title=<?php echo $title;?>" method="POST">

and my php is
if ($_POST["submit"]) {
    $rating = $_POST['star'];
    $title = $_GET['title'];
    $verification = ($_GET['verification']);
} else {
    //run the page like usual
}

After testing, I found that onclick, it runs the form action, but on the php side, it goes to "else" where is runs the page like usual instead. Any ideas?
Comment: the `name` element of `` is not submitted/posted. you could add a hidden element with name submit - `` OR just use your radio name `if(isset($_POST['star']))`
Comment: It seems the form element has an action attribute with no closing quote and no space before the method attribute, probably causing the form to be submitted as `GET` instead
Comment: Sending something in the URl like `?id=thisthat` doesn't make it a `POST`
Comment: also your `action` is missing a closing quote, and no space before `method`.
Comment: the form action looks wrong
Comment: `$POST['submit']` assumes you have an input in your form with the name `submit`. Which as you said, you don't have, so your logic moves straight to the else statement.
Comment: my mistake. was typing too fast. Anyway, I've used Sean's answer with the isset. Thanks
Answer: Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement.
If you want to check if the form was posted then you should instead check for:
if (!empty($_POST)) {}

or
if ($_SERVER['REQUEST_METHOD'] == 'POST') {}

Answer: The form element seems to have invalid attributes, missing a quote and space.
It's generally easier to write a little more code, and keep it clearer
<?php
   $url = "http://example.com/page.php?id=". $urlid ."&title=". $title;
?>

<form name="submit" action="<?php echo $url; ?>" method="POST">

Answer: Since you are checking with -
if ($_POST["submit"]) { // this checks whether there is any item named 'submit' inside the POST or not
} else {
    //run the page like usual
}

The easiest would be to put a hidden item with name submit so that the check validates to true-
<form .. >
     ....
     <input type='hidden' name='submit' value='submit' />
</form>

Cant submit form


Redirecionamento de URLS

Question: Bom dia!
Tenho 2 sites wordpress (1 vai ser apagado) e estão com posts duplicados, pôs exportei e importei no outro. Existe uma maneira de eu redirecionar todos as urls de uma vez? Exemplo:
Tudo que for www.site1.com vire www.site2.com, sendo assim se tivermos uma URL: www.site1.com/olamundo ela viraria www.site2.com/olamundo
Tem como fazer redirecionamento 301, de alguma forma? São mais de 500 posts, e precisaria redirecionar tudo de uma vez.
Answer: Através do .htaccess você pode fazer o redirecionamento
<code>Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^DOMINIOANTIGO\.com$ [NC]
RewriteRule ^(.*)$ http://NOVODOMINIO.com [R=301,L]
</code>
Comment: Acredito que RewriteRule ^(.*)$ http://www.novodominio.com/$1 [R=301,L] deva resolver
Comment: Jefferson, obrigado! Como ficaria se eu tivesse um dominio assim: www.meusite.com.br/blog e www.meusite2.com.br/blog ?

Redirecionamento de URLS


Passenger not working with SSL on Apache 2

Question: I have a Rails app running on Passenger; It works as expected over unencrypted connections. I also have a working Apache SSL setup; I can access any static file available via http with https. When I try to access the Rails app via https, I get a 403 error (Directory index forbidden by rule). Turning on indexes for the directory simply causes Apache to display an index. I do have <code>+ExecCGI</code> set for the appropriate directory in the SSL version of the VirtualHost directive.
I'm sure there's something obvious I'm overlooking. I'm just not sure where I need to be looking.
Answer: There were domain-wide VirtualHost directives for each of SSL and non-SSL. The non-SSL version contained a RailsBaseURI directive, while the SSL version did not. Passenger requires the RailsBaseURI directive to work.


HTTP request status fails, but update checking works manually

Question: I have a problem with my Drupal 7 (multi-site) installation on a root-server. The HTTP request status shows "failed" on the status page. However, I am able to check for updates manually when logged in without a problem, so Drupal actually is allowed to access other sites.
I am having problems with automatic update-checks via cron though. Sometimes they work, sometimes they work only partially. This results in an error-report being sent sometimes via email, which is quite annoying since I only want this for security updates.
Does anyone know how to solve this? We do have a root-server, however I'm not the admin and other non-drupal sites run on it too, so I can't just play around with server-settings, I would have to request changes (I can see phpInfo() though, if that helps).
The weird thing is that updates do work manually, and at least partially when checked via cron (I also disabled any external cron-job, so it's only triggered via poor-man's-cron). Could it be a Drupal core problem after all, maybe related to this: https://drupal.org/node/965078?
-- Drupal 7.27, all modules up-to-date
Answer: This is most likely caused by an old issue, a time-out of 5 seconds which is easily exceeded when checking for updates via poor-man's cron on sites with more than a few modules. See this issue.
Easiest solution is probably to use real cron jobs if possible to avoid this altogether, although there are other suggestions on the linked site. Drupal 7.28 finally increased the limit to 30 seconds, in many cases this might suffice. However it may lead to a page load slow-down, so imho it's better to avoid poor man's cron.


prefilling SESSION[SESS_PREFIX

Question: On my home page there is a link to another page.. when I go from my homepage to let say the order page..  the order page is working..
But when I go to my order page directly.. I got an error:
 Notice: Undefined index: banner_type  on line 33
// line 33
    $_SESSION[SESS_PREFIX .'type'] = $_POST['banner_type'];
the prefill must be kozijnen.. what code can i use for the order page to work. when I visit it directly?
<code>if ( isset ( $_SESSION[SESS_PREFIX .'type'] ) ) {

    // check flyer

    if ( $_SESSION[SESS_PREFIX .'type'] == "kozijnen" ) {
</code>
I need to hard code the kozijnen into my order page..
this is a part off the code from my home page:

                                $value ) {

                                    // output
                                    //echo '';

                                }

                                ?>

                                    Postcode

                                    Straal

                                        10 km
                                        25 km
                                        50 km
                                        100 km
                                        Overal

                                    Werkzaamheden

                                        $value ) {
                                            echo ''. $value .'';
                                        }
                                        ?>

                                --->

and this from my order page..
/ chek sessions step1
if ( !isset($_SESSION[SESS_PREFIX .'postal']) OR !isset($_SESSION[SESS_PREFIX .'radius']) OR !isset($_SESSION[SESS_PREFIX .'type']) ) {
<code>// fill in

$_SESSION[SESS_PREFIX .'type'] = $_POST['banner_type'];

// check isset submit

if ( isset ( $_POST['banner_search_submit'] ) ) {

    header("Location: ". $_SERVER['REQUEST_URI']);

}
</code>
}
// check step 2
if ( isset ( $_POST['gotostep2'] ) OR isset ( $_POST['adjuststep1'] ) ) {
<code>$_SESSION[SESS_PREFIX .'type'] = $_POST['type'];
</code>
}
--
/ check type isset
//echo ( isset ( $$_SESSION[SESS_PREFIX .'type'] = "kozijnen" ) {
if ( isset ( $_SESSION[SESS_PREFIX .'type'] ) ) {
<code>// check flyer

if ( $_SESSION[SESS_PREFIX .'type'] == "kozijnen" ) {
</code>
Comment: I'm not sure I understand your question.
Comment: If your homepage is setting session variables needed to the order page to work, it's probably the correct flow and you should not mess with it. If that's unavoidable, you should present more explanations on your expectations and more of your code.
Comment: In that case, going from one place to another creates an array index (inside some array we can't know for sure because you didn't specified it) called "banner_type", that when you access it directly, cannot be set.
Comment: I still don't get your question, but perhaps this is what you need: `$_SESSION[SESS_PREFIX .'type'] = isset($_SESSION[SESS_PREFIX .'type']) ? $_SESSION[SESS_PREFIX .'type'] : 'kozijnen';`
Comment: Yes Epodax! it working! thank you! it was difficult to explain sorry for that
Answer: Deducted from the comments, what you were looking for is called a ternary operator
It can be used in a different set of ways but in general it's used to assign a "default" value if no value is present.
And one of the way it works are like so:
<code>$value = (CHECK) ? <VALUE IF CHECK PASSES> : <VALUE IF CHECK FAILS>;
</code>
As stated in comments you should / could use it like so:
<code>$_SESSION[SESS_PREFIX .'type'] = isset($_SESSION[SESS_PREFIX .'type']) ? $_SESSION[SESS_PREFIX .'type'] : 'kozijnen';
</code>

prefilling SESSION[SESS_PREFIX


Setting up Pressflow 6 with Vagrant VM

Question: Has anyone managed to get Pressflow built into a Vagrant box? I'm new to vagrant and am completely failing at this. Have looked into both Puppet and Chef to configure it (either would be fine) and can't seem to find a recipe that does the trick.
This example.make file seems to describe a way to do this with Puppet, but then I have the added complexity of putting Drush on the vagrant box and I'm not really even sure what to do with the ".make" file.
Any pointers are appreciated - thanks!
EDIT:
Here's the state of my Vagrantfile:
<code># -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant::Config.run do |config|

 # Every Vagrant virtual environment requires a box to build off of.
 config.vm.box = "quetzal64"

 # Boot with a GUI so you can see the screen. (Default is headless)
 # config.vm.boot_mode = :gui

 # Forward a port from the guest to the host, which allows for outside
 # computers to access the VM, whereas host only networking does not.
 config.vm.forward_port 80, 8080
 config.vm.forward_port 3036, 3037

 # somehow specify to use drush, puppet, and the example.make file?

end
</code>
and example.make:
<code>; Core version
; ------------
core = 6.x

; API version
; ------------
api = 2

; Core project
; ------------
; Use Pressflow instead of Drupal core:
projects[pressflow][type] = "core"
projects[pressflow][download][type] = "file"
projects[pressflow][download][url] = "http://launchpad.net/pressflow/6.x/6.15.73/+download/pressflow-6.15.73.tar.gz"
</code>
Answer: After trying quite a few things, we ended up putting together a shell script to do the provisioning. Most of it is specific to our application, but here are the relevant excerpts for anyone who might want to try this:
(there is probably some configuration necessary that this script omits)
<code>#!/bin/sh

cd ~

echo "Beginning fresh install..."
sudo apt-get update

echo "Installing base utilities..."
sudo apt-get -qq -y install zip unzip

# Install LAMP stack
echo "Installing LAMP stack..."
sudo apt-get -qq -y install tasksel && sudo tasksel install lamp-server
sudo apt-get -qq -y install php5-gd php-pear php5-xdebug php5-dev php5-curl
sudo a2enmod rewrite # Enable apache rewrite module

# Install pressflow if necessary
echo "Downloading and installing pressflow..."
wget -qNO /tmp/pressflow.tar.gz https://github.com/pressflow/6/archive/pressflow-6.26.109.tar.gz
sudo rm -rf /tmp/pressflow && mkdir /tmp/pressflow
tar -xzf /tmp/pressflow.tar.gz -C /tmp/pressflow
sudo rm -rf /tmp/pressflow/6-pressflow-6.26.109/sites/all
rsync -a /tmp/pressflow/6-pressflow-6.26.109/* ~/yoursitepath # !! Your Drupal directory here.
sudo rm -rf /tmp/pressflow /tmp/pressflow.tar.gz

# Update php.ini
echo "Updating PHP config options..."
PHPINILOC="/etc/php5/apache2/php.ini"
sudo sed -i 's/memory_limit = 128M/memory_limit = 1024M/g' $PHPINILOC
sudo sed -i '/error_reporting = E_ALL.*/c\error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT' $PHPINILOC

# Create database schemas
echo "Creating databases..."
mysql -uroot -e"CREATE DATABASE IF NOT EXISTS ourfa5_drupal; CREATE DATABASE IF NOT EXISTS stats;"

# Here, you'll probably need to download any default tables needed by your
#   application, update /etc/hosts, etc.. This portion of the script is
#   specific to our application so I've left it out.

# Restart apache for good measure
sudo service apache2 restart

sudo apt-get upgrade
</code>

Setting up Pressflow 6 with Vagrant VM


Scaling a normal distribution while using EWMA

Question: I have a time series of daily data and am assuming each point in the time series is normally distributed. If I have a distribution of the daily data and want to scale this to cover a month (30 days) I believe I just scale the standard deviation by square root of 30. I think this assumes the data points are independently distributed. If I use an exponentially weighted moving average to calculate the standard deviation can I still scale the daily data to monthly by multiplying by square root 30?
Answer: Yes you can: you're still getting a one day stddev estimate, which refers to the very same quantity, just obtained by another route with different precision and calculation method. How to project to 30 days is not affected from the origination of such quantity.
What instead would affect scaling are e.g. different distributional assumptions, or autocorrelation. See also Meucci 2011 - Visualizing the Propagation of Risk - Square-Root Rule, Covariances and Ellipsoids and Meucci 2010 - Annualization and General Projection of Skewness, Kurtosis and All Summary Statistics.
On the other hand, consider why are you using EWMA: you probably have reasons to think that your variance is not constant. If variance was constant then you should use all data with constant weighting to get best statistical efficiency. Therefore you would be better off fitting a heteroschedastic model such as GARCH and then considering its forecast distribution at 30 days, which in this case would NOT be just the $\sqrt{T}$ extrapolation from the 1-day variance, but would also include additional uncertainty in the future variance evolution (plus other components too).
Comment: Updated with some info on the context.
Comment: how would daily sddev scale to the monthly equivalent with GARCH? We would no longer be talking about a normal distribution would we?
Comment: I don't know if there could be an equivalent scaling in closed form. But you could always simulate the fitted GARCH and estimate (semi)empirically.


Como codificar e decodificar strings base64 em C?

Question: Preciso codificar (e decodificar) um JSON para ser transmitido da Web para um microcontrolador. O JSON que estou enviando é criptografado com o AES 128, mas o cyphertext contém caracteres não imprimíveis e obtive alguns problemas com isto. Por exemplo, quando tento receber estes dados no microcontrolador a decriptação não se dá de forma correta. Entretanto, se eu encripto e decripto uma string dentro do microcontrolador, o processo ocorre normalmente.
Acredito que o problema seja a codificação dos caracteres, pois existem caracteres não imprimíveis que não são transmitidos. Preciso então efetuar as seguintes etapas, exatamente nesta ordem:

Criptografar um texto utilizando o AES 128
Codificar o cyphertext em base64 para ser transmitido via Web
Receber os dados no microcontrolador
Decodificar o cyphertext em base64, para sua representação natural
Decriptografar o cyphertext usando o AES 128

Minha dúvida é: como codificar e decodificar strings base64 em C? Existe alguma biblioteca para isto?
Edit: Existe alguma forma otimizada de fazer isto? Encontrei um exemplo que contem o algoritmo que decodifica, mas ele usa uma matriz enorme para fazer isto.
Comment: Se estás a usar OpenSSL para criptografar com AES 128, podes usá-lo também para [base64](https://www.openssl.org/docs/manmaster/crypto/BIO_f_base64.html).
Comment: glib tambem tem funçoes para base46 http://developer.gnome.org/glib/2.28/glib-Base64-Encoding.html
Answer: Avelino, não julgue um código pelas suas matrizes!
O exemplo que você encontrou é baseado no arquivo ap_base64.c do projeto APR - Apache Portable Runtime (veja aqui o código original), que por sua vez, é bastante difundido e usado em diversos outros projetos. Ele foi implementado em C puro e não depende de nenhuma outra biblioteca externa.
Essa matriz enorme cheia de números mágicos que você mencionou é capaz de proporcionar um aumento considerável de performance no processamento de dados em base64, o que a torna bastante viável.
Minha sugestão é: Não tenha preconceito com esse código, ele é rápido, portável e bastante eficiente.
Segue (portanto) o código propriamente dito reescrito de forma a trabalhar somente com ASCII:
Header base64.h:
/*
    base64.h
*/

#ifndef __BASE64_H__
#define __BASE64_H__

int base64decode_len( const char * bufcoded );
int base64decode( char * bufplain, const char * bufcoded );

int base64encode_len( int len );
int base64encode( char * encoded, const char * string, int len );

#endif

/* fim-de-arquivo */

Implementação base64.c:
/*
    base64.c
*/

#include <string.h>

#include "base64.h"

static int base64decode_binary( unsigned char * bufplain, const char * bufcoded );
static int base64encode_binary( char * encoded, const unsigned char * string, int len );

static const char basis_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static const unsigned char pr2six[256] =
{
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
    64,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
    64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
    64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};

static int base64decode_binary( unsigned char * bufplain, const char * bufcoded )
{
    int nbytesdecoded;
    register const unsigned char *bufin;
    register unsigned char *bufout;
    register int nprbytes;

    bufin = (const unsigned char *) bufcoded;

    while (pr2six[*(bufin++)] <= 63);

    nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
    nbytesdecoded = ((nprbytes + 3) / 4) * 3;

    bufout = (unsigned char *) bufplain;
    bufin = (const unsigned char *) bufcoded;

    while (nprbytes > 4)
    {
        *(bufout++) = (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
        *(bufout++) = (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
        *(bufout++) = (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);

        bufin += 4;
        nprbytes -= 4;
    }

    /* Note: (nprbytes == 1) would be an error, so just ingore that case */
    if (nprbytes > 1)
    {
        *(bufout++) = (unsigned char) (pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4);
    }

    if (nprbytes > 2)
    {
        *(bufout++) = (unsigned char) (pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2);
    }

    if (nprbytes > 3)
    {
        *(bufout++) = (unsigned char) (pr2six[bufin[2]] << 6 | pr2six[bufin[3]]);
    }

    *(bufout++) = '\0';
    nbytesdecoded -= (4 - nprbytes) & 3;

    return nbytesdecoded;
}

static int base64encode_binary(char *encoded, const unsigned char *string, int len )
{
    int i;
    char *p;

    p = encoded;

    for (i = 0; i < len - 2; i += 3)
    {
        *p++ = basis_64[(string[i] >> 2) & 0x3F];
        *p++ = basis_64[((string[i] & 0x3) << 4) | ((int) (string[i + 1] & 0xF0) >> 4)];
        *p++ = basis_64[((string[i + 1] & 0xF) << 2) | ((int) (string[i + 2] & 0xC0) >> 6)];
        *p++ = basis_64[string[i + 2] & 0x3F];
    }

    if (i < len)
    {
        *p++ = basis_64[(string[i] >> 2) & 0x3F];

        if (i == (len - 1))
        {
            *p++ = basis_64[((string[i] & 0x3) << 4)];
            *p++ = '=';
        }
        else
        {
            *p++ = basis_64[((string[i] & 0x3) << 4) | ((int) (string[i + 1] & 0xF0) >> 4)];
            *p++ = basis_64[((string[i + 1] & 0xF) << 2)];
        }

        *p++ = '=';
    }

    *p++ = '\0';

    return p - encoded;
}

int base64decode_len( const char * bufcoded )
{
    int nbytesdecoded;
    register const unsigned char *bufin;
    register int nprbytes;

    bufin = (const unsigned char *) bufcoded;

    while (pr2six[*(bufin++)] <= 63);

    nprbytes = (bufin - (const unsigned char *) bufcoded) - 1;
    nbytesdecoded = ((nprbytes + 3) / 4) * 3;

    return nbytesdecoded + 1;
}

int base64decode( char * bufplain, const char * bufcoded )
{
    int len;
    len = base64decode_binary((unsigned char *) bufplain, bufcoded);
    return len;
}

int base64encode_len( int len )
{
    return ((len + 2) / 3 * 4) + 1;
}

int base64encode( char * encoded, const char * string, int len )
{
    return base64encode_binary(encoded, (const unsigned char *) string, len);
}

/* fim-de-arquivo */


Why are harmonics on guitar easier with distortion?

Question: Background
Something I've noticed playing electric guitar is that natural harmonics are easier to achieve under heavy distortion. For the sake of disambiguation, when I use the word harmonic, I mean plucking a string at the same time as you release your finger from the string at a particular fret, producing a noise like a ringing bell.
To elaborate on the phenomena, playing harmonics on the acoustic guitar is typically hard for me unless they're performed at the 1/2, 1/3, or 1/4 ratios (12th, 7th, and 5th) fret. Still, the 12th is easier than the 7th and the 7th is easier than the 5th. Going further toward the nut is much more difficult (at least for me personally).
Playing electric guitar on a clean setting is mostly the same as the acoustic. However, as soon as gain is increased a little on the electric, the harmonics become easier. Using an effects pedal meant for playing metal music, the most intense distortion I have, the harmonics that are hardest to achieve are now easy. Playing at the second fret produces an extremely loud sound, even louder than playing a note normally.
Running Ideas
The best attempt at an answer I have at the moment is that the distortion pedals add frequencies that could resonate with the imperfectly played harmonic (those closer to the nut are harder to achieve) and produce positive feedback to make the note ring louder. However, I tested this by playing a recording of the cleanly played harmonic into the amp, and the distortion still had the same effect. This is a contradiction because the guitar is not live in this scenario to create the positive feedback. So, this effect is plausible but negligible at best.
My other idea is that the plucking noise of a harmonic is drowned out by the pedal which produces a sort of ambient fuzz, while the note is compressed to ring loudly. However, this is just my best guess.
Any ideas?
Comment: Playing a harmonic - you don't need to take your finger off as you play. That point along the string (the node) isn't moving. In fact, you can put your finger back on again gently, and it'll carry on sounding.
Comment: I have seen/heard electric guitar players on video perform harmonics with great ease and at fretboard locations I had not realized would produce the harmonic note phenomenon.  I am guessing an effects device is making this possible but not necessarily a distortion effect.  It may be use of compression that makes harmonics so easy to play.  In any case, it seems without effects enhancement, playing harmonics on guitar as if it were another instrument, would not be possible without effects.
Answer: Distortion has a compressing effect- you may notice that noise gets louder when you turn up your gain, while (after a point) the guitar does not get that much louder since you're pushing up against the "ceiling" created by your distortion circuit.  It's not just the noise that gets louder, but every quiet sound, including harmonics.
Here's a demonstration of @Tetsujin 's conjecture- you will hear a dry sampled guitar sound, then that sound through (cheesy) distortion, then that sound through compression.  You will notice that the harmonic rings out clearly even without distortion, if there is enough compression.
Combine that effect with the added harmonics that distortion adds and you can easily get clear harmonics.  Distortion doesn't really make harmonics easier to play, but it will help your harmonics (even if played less than perfectly) ring out clearly.
Answer: Distortion greatly amplifies harmonics relative to the basic frequency, so naturally if you play harmonics through a distortion pedal, their volume will be much higher than without it.
Comment: Distortion generally adds a lot of compression too. I've never tested with just a compressor, but it wouldn't surprise me if that would work almost as well.
Comment: @Tetsujin it would be interesting to try, but my guess would be that it wouldn't work so much after all: in case of distortion, the compression effect is due to the fact that harmonics are maxed out and clipped at maximum volume (hence both distortion and compression result). In the case of a regular compressor there is only an overall change of the volume envelope, and while that will give a bit more sustain to a faint harmonic, it will never come close to the amplification of that harmonic that distortion does. But that's just my guess, someone should try it and post a video...
Comment: "Distortion greatly amplifies harmonic" is not true in general. Rather, distortion adds _new_ harmonics, it is for that reason the result is richer in harmonics (which just happen to be on the same frequencies as the original harmonics). Now, some overdrive implementations do also include a mid/treble boost before the actual clipping, but this is basically just a simple equaliser, so your answer amounts to "why are harmonics on guitar easier with high-mid boosted equaliser". That is certainly not the main reason why distortion can make harmonics easier to bring out.
Comment: This doesn't really answer the question, which I think is a bit of a red herring.  Distortion does not make the mechanics of a harmonic easy.
Answer: Define what you mean by "easier"?  I have never experienced this in my life and I've played guitar for over 40 years.  It is perhaps possible that some effects accentuate the higher overtones of a plucked note making them more "trebley" but the mechanics of creating a true harmonic are not in any way enhanced by effects.  I can generate them just as easily and with sustain on a classical guitar.
Comment: My understanding is that there's a greater error tolerance for placement of your finger at the twelfth fret than the second fret. This effect makes playing at the twelfth fret "easier" to me, as it takes less precision to get a ringing noise. This is important because I find the quality of the harmonic to be the ratio of ringing noise to plucking noise.
Comment: I don't know how to interpret that.  If you are allowed a greater error tolerance how do you know that what you are hearing is a real harmonic and some other high frequency noise?  The physics of it is the same and I would think that you still need to nail it right on to get a good tone.  I play all kinds of music, metal included, so I've used distortion and I cannot say I am familiar with this phenomenon.
Comment: The apparent pitch doesn't change. Try putting your finger on the twelfth fret for a harmonic and move it left and right. There's room to move it where the pitch sounds the same. Then, try putting your finger on the second fret and play a harmonic. Test the range in which you get the same pitch. When I personally try this experiment, I get the same pitch at a greater range of positions near the sweet spot on the twelfth fret than the same experiment repeated at the second. I assume it's the same as others, but I could be doing something wrong.
Comment: That has nothing to do with distortion


Is it ok to fit a Bayesian model first, then begin weakening priors?

Question: When doing frequentist stats, there is a long list of big no-nos, like looking at the results of statistical tests before deciding to collect more data. I'm wondering generally if there are a similar list of no-nos for the methodologies involved in Bayesian statistics, and specifically whether the following is one of them.
I've realized recently that for some of the models I've been fitting, my process has been to first fit the model with informative priors to see if it works or blows up, and then weaken the priors either to uninformative or weakly informative and refit the model.
My motivation for this really has to do with the fact that I'm writing these models in JAGS/Stan, and in my mind I've been treating it more like a programming task than a statistical one. So, I do a first run, sort of rigging it to converge quickly by using informative priors, making it easier to catch errors in the model I've written. Then, after debugging the model, I refit it with uninformative, or weakly informative priors.
My question is whether or not I'm breaking some serious rules with this process. For example, for my inferences to be valid, and to avoid exploiting researchers' degrees of freedom, do I need to commit to specific priors before are start fitting any models?
Comment: As a humorous aside (I hope) here is a [poem I wrote](http://voices.yahoo.com/ode-bayesian-4610651.html?cat=42). (Yes, I know it's not an ode)
Comment: @PeterFlom, oh, that's ominous.
Answer: Subjective Bayesians might disagree, but from my perspective, the prior is just a part of the model, like the likelihood. Changing the prior in response to model behavior is no better or worse than changing your likelihood function (e.g. trying different error distributions or different model formulations).
It can be dangerous if it lets you go on a fishing expedition, but the alternatives can be worse.  For example, in the case you mentioned, where your model blows up and you get nonsensical coefficients, then you don't have much choice but to try again.
Also, there are steps you can take to minimize the dangers of a fishing expedition somewhat:

Deciding in advance which prior you'll use in the final analysis
Being up-front when you publish or describe your analysis about your whole procedure
Doing as much as possible with either simulated data and/or holding out data for the final analysis.  That way, you won't contaminate your analysis too much.
Answer: I think you're okay in this case for three reasons:

You're not actually adjusting your priors in response to your results. If you said something like, "I use XYZ priors and depending on the rate of convergence and my DIC results, I then modify my prior by ABC," then I'd say you were committing a no-no, but in this case it sounds like you really are not doing that.
In a Bayesian context, priors are explicit. So it's possible for you to tweak your priors improperly, but the resultant priors will always be visible for inspection by others who can question why you have those particular priors. Maybe I'm naive here, since it's easy to glance at something like a prior and say, "Hmm, looks reasonable" simply because someone offered it up, but...
I think what you're doing is related to Gelman's (and others') advice to build up a JAGS model piece-by-piece, first working with synthetic data, then real data, to make sure you don't have a specification error. That's not really a factor in frequentist methodology, and it's not really an experimental methodology.

Then again, I'm still learning this stuff myself.
P.S. When you say you originally rig it to converge quickly with "informative priors", do you mean actually informative priors that are motivated by the problem at hand, or just priors that for arbitrary reasons strongly push/restrict the posterior to speed up "convergence" to some arbitrary point? If it's the first case, why are you then moving away from these (motivated) priors?
Answer: If you experiment with priors and select one in terms of its performances on the data at hand, it is no longer a "prior". Not only does it depend on the data (as in an empirical Bayes analysis), but it also depends on what you want to see (which is worse). In the end, you do use Bayesian tools, but this cannot be called a Bayesian analysis.
Comment: As I understand the OP, he is not using one prior and looking at the results and deciding that another prior will give him better results. He is using an artificial prior to see that his model is properly coded, then switching to his actual prior for analysis. Perhaps if he also used synthetic data in his first step, then switched to both his actual prior and his actual data in the second step, it would be more acceptable?
Answer: I would say no, you do not have to commit to specific priors.  Generally during any Bayesian data analysis you should perform an analysis of the sensitivity of the model to the prior.  That would include trying various other priors to see what happens to the results. This might reveal a better or more robust prior that should be used.
The two obvious "no-no's" are: playing around with the prior too much to get a better fit, resulting in over fit and changing the other parameters of the model to get a better fit. As an example of the first: changing an initial prior on the mean so that it is closer to the sample mean. For the second:  changing your explanatory variables/ features in a regression to get a better fit. This is a problem in any version of regression and basically invalidates your degrees of freedom.
Comment: +1 for mentioning sensitivity analysis. You should know how much your results are dependent on the priors used...
Comment: One useful idea is to ask yourself *what priors could be accepted by people sceptical to your results*?
Answer: I think this might be a no no independent of the Bayesian school.  Jeffreys would want to use noninformative priors. Lindley might want you to use informative priors.  Empirical Bayesians would ask that you let the data influence the prior.  But I think although each school is making a different suggestion about the choice of prior, they all have an approach that does not mean that you can take the prior and keep tweaking it until you get the results you want.  That would definitely be like looking at the data and contnuing to collect data and test until you reach your preconceived notion of what the answer should be.
Frequentist or Bayesian it doesn't matter i don't think anyone would want you to play tricks with (or massage) the data.  Maybe this is something we all can agree on and Peter's funny poem is really apropo.


leaflet how to get latlng into html variable

Question: I can't figure out how to extract a mouse click into latlng and then into a html variable. Here' what I've done (from post How to get the Lat, Long of a clicked location using leaflet Api):
var lat = map.on('click', function(e) {
    alert(e.latlng[0]); });

In short, I can't figure out how to use leaflet to write to a variable. On then use that variable in html:

html stuff works, but not the leaflet things.
Thanks,
Dawg
Comment: I believe you've got some concepts wrong. There's no such thing as an html variable, just Javascript ones. Anyway, what exactly are you trying to achieve? Write the clicked upon coordinates onto the webpage?
Answer: you should use console.log(e); to check your reference is valid.
try
map.on('click', function(e) {
    alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)
}

or in your case
map.on('click', function(e) {
    var lat = e.latlng.lat;
}


Create a simple quiz for each video

Question: I have a "video" content type, and I want from users watching my videos to answer some questions related to each single video.
Can you advice me, how can I create a quiz for each single video content ?
Is there a module (I tried the quiz module but it's very complicated) to do that, or any other way will be apprecited.
thanks in advance.
Comment: Why don't you use the simple `comment` module?
Answer: You can use the Webform module to create a quiz.
Here is a quote about it (from the module's project page):

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
Some good examples could be contests, personalized contact forms, or petitions. Each of these could have a customized form for end-users to fill out. If you need to build a lot of customized, one-off forms, Webform is a more suitable solution than creating content types and using CCK or Field module.
Comment: This is a Q+A site, not a forum.  Please add further explanations about how to your answer to the body by clicking the "Edit" button below your answer.
Comment: How can I attach the created form with a specific node ?
Comment: create a views block and filter the webform, to attach the webform you can use views_embed_views or https://drupal.org/project/views_field you can add views field in your video content type
Comment: download the module and enabled it, then add new field views field and configured it base on your needs.

Create a simple quiz for each video


Threshold for LDA in the case of three classes

Question: The result of discriminant analysis for the three classes are two discriminant functions LD1 and LD2.
In the case of two classes, there is one discriminant function LD1, and the threshold of discrimination can be calculated as follows:
$$
C = \frac{1}{2}(M_{1} + M_{2})
$$
M1 is the mean value of LD1 estimates for class 1, and M2 for class 2.
Please, help me understand how, with LD1 and LD2, calculated threshold of discrimination for the case of three classes.
UPD

How I can find the equations of these thresholds lines on a graph?
Answer: No. The threshold can not be "calculated" by that formula. That formula is one (!) possibility for setting that threshold.
There is an enormous amount of misinformation regarding thresholds for classification. I recommend reading this earlier thread. It does not explicitly address your three-level classification case, but can be applied to it: the solution is to think about your costs of misclassification and set thresholds accordingly.
Even better is to discard thresholds in the statistical analysis entirely and work with purely probabilistic predictions.
Comment: Very grateful for your answer. It helped me a little to understand how I can use probabilistic prediction in my case.


ERROR NullInjectorError: R3InjectorError(AppModule)[ VendaComponent -> VendaComponent]No provider for VendaComponent!

Question: Estou criando uma pagina para venda e quando clico pra adicionar produto é para abrir uma tela com os produtos cadastrados. No tutorial que estava seguindo ele adicionou no construtor uma classe que possui o array com os produtos, no meu caso fiz o array dentro do Component, só que está dando o erro que coloquei no titulo.
import { Component, OnInit, Inject } from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import { ItemProduto } from '../item-produto';
import { HttpClient } from '@angular/common/http';
import { ProdutoModel } from '../produto-model';
import { NgForm } from '@angular/forms';
import { VendaComponent } from '../venda/venda.component';

@Component({
  selector: 'app-item-produto',
  templateUrl: './item-produto.component.html',
  styleUrls: ['./item-produto.component.css']
})
export class ItemProdutoComponent implements OnInit {
  formData:ItemProduto;
  listaProdutos: ProdutoModel[];
  isValid: boolean = true;

  url = 'http://localhost:8080/api/produtos';

  constructor(private http: HttpClient,
    @Inject(MAT_DIALOG_DATA) public data,
    public dialogRef:MatDialogRef<ItemProdutoComponent>,
    private vendaComponent:VendaComponent) { }
   // private vendaComponent:VendaComponent

  ngOnInit(){
    this.getProdutos().then(res => this.listaProdutos = res as ProdutoModel[]);
    if(this.data.itemProdutoIndex==null)
    this.formData ={
      IDITEMPRODUTO: null,
      IDVENDA : this.data.IDVENDA,
      IDPRODUTO:0,
      QUANTIDADE:0,
      ITEMNOME:''
    }
    else
    this.formData = Object.assign({},this.vendaComponent.itemProduto[this.data.itemProdutoIndex]);
  }
  //,this.vendaComponent.itemProduto[this.data.itemProdutoIndex]
  getProdutos(){
    return this.http.get(this.url).toPromise();
  }

  atualizarNomeItem(ctrl){
    if(ctrl.selectedIndex == 0) {
      this.formData.ITEMNOME = '';
    }else{
      this.formData.ITEMNOME = this.listaProdutos[ctrl.selectedIndex-1].NOME;
    }
  }

  onSubmit(form:NgForm){
    if(this.validarForm(form.value)){
      //if(this.data.itemProdutoIndex==null)
      //this.vendaComponent.itemProduto.push(form.value);
      //else
        //this.vendaComponent.itemProduto[this.data.itemProdutoIndex] = form.value;
      this.dialogRef.close();
    }
  }

  validarForm(formData: ItemProduto){
    this.isValid = true;
    if(formData.IDITEMPRODUTO == 0)
      this.isValid = false;
    else if(formData.QUANTIDADE == 0)
      this.isValid = false;
    return this.isValid;
  }

}

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule} from '@angular/common/http';

import { AppRoutingModule} from './app-routing.module';
import { AppComponent } from './app.component';

import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { ModalModule } from 'ngx-bootstrap/modal';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDialogModule } from '@angular/material/dialog';

import { HomeComponent } from './home/home.component';
import { EditarComponent } from './editar/editar.component';
import { ClienteComponent } from './cliente/cliente.component';
import { ProdutoComponent } from './produto/produto.component';
import { ListagemClientesComponent } from './listagem-clientes/listagem-clientes.component';
import { VendaComponent } from './venda/venda.component';
import { ItemProdutoComponent } from './item-produto/item-produto.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    EditarComponent,
    ClienteComponent,
    ProdutoComponent,
    ListagemClientesComponent,
    VendaComponent,
    ItemProdutoComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    BsDropdownModule.forRoot(),
    TooltipModule.forRoot(),
    ModalModule.forRoot(),
    BrowserAnimationsModule,
    MatDialogModule,
    ReactiveFormsModule
  ],
  entryComponents: [ItemProdutoComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        ReactiveFormsModule,
        FormsModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

Aqui está o erro em completo que está me retornando
ERROR NullInjectorError: R3InjectorError(AppModule)[VendaComponent -> VendaComponent -> VendaComponent]:
  NullInjectorError: No provider for VendaComponent!
    at NullInjector.get (http://localhost:4200/vendor.js:32682:27)
    at R3Injector.get (http://localhost:4200/vendor.js:46410:33)
    at R3Injector.get (http://localhost:4200/vendor.js:46410:33)
    at R3Injector.get (http://localhost:4200/vendor.js:46410:33)
    at NgModuleRef$1.get (http://localhost:4200/vendor.js:63757:33)
    at Object.get (http://localhost:4200/vendor.js:61599:35)
    at getOrCreateInjectable (http://localhost:4200/vendor.js:36209:39)
    at Module.ɵɵdirectiveInject (http://localhost:4200/vendor.js:50327:12)
    at NodeInjectorFactory.ItemProdutoComponent_Factory [as factory] (http://localhost:4200/main.js:647:579)
    at getNodeInjectable (http://localhost:4200/vendor.js:36354:44)
defaultErrorLogger @ core.js:5871

Comment: componentes não sao injetaveis
Comment: coloque esses dados num serviceo
Comment: Bom dia!
Tive o mesmo problema e você deverá incluir "providers: [VendaComponent]" no AppModule.
Answer: Você precisa colocar o
@Injectable({
  providedIn: 'root'
})

no VendaComponent antes de exportar, e também importar o
import {Injectable} from '@angular/core';

Answer: Nunca dependa de outro Component no construtor, se quiser mesmo usar esse componente instancie ele assim:
vendaComponent:VendaComponent = new VendaComponent();


Unable to import opengl.gl in python on macos

Question: I am using OpenGL to render a scene in python. My code works perfectly fine on windows but, for some reason, I'm having issues when importing opengl.gl on MacOS.
The issue arises when calling from OpenGL.GL import ... in both python scripts and the python console.
More specifically here is the exact call in my script:
from OpenGL.GL import glGenBuffers, glBindBuffer, glBufferData, \
    glGenVertexArrays, glBindVertexArray, glEnableVertexAttribArray, glVertexAttribPointer, \
    glDrawArrays, glUseProgram, glEnable, glDisable, \
    GL_ARRAY_BUFFER, GL_STATIC_DRAW, GL_DEPTH_TEST, \
    GL_FLOAT, GL_FALSE, \
    GL_TRIANGLES, GL_LINES, GL_LINE_STRIP

This results in the following error:
       Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 35, in GL
    return ctypesloader.loadLibrary(
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/ctypesloader.py", line 36, in loadLibrary
    return _loadLibraryWindows(dllType, name, mode)
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/ctypesloader.py", line 89, in _loadLibraryWindows
    return dllType( name, mode )
  File "/firstname.lastname@example.com/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ctypes/__init__.py", line 373, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: ('dlopen(OpenGL, 10): image not found', 'OpenGL', None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/iyadboustany/Desktop/lensmaster/Lensmaster.py", line 18, in <module>
    from MainWindow import MainWindow
  File "/Users/iyadboustany/Desktop/lensmaster/MainWindow.py", line 14, in <module>
    from Robot import Robot
  File "/Users/iyadboustany/Desktop/lensmaster/Robot.py", line 8, in <module>
    from Graphics.Scene import DHNode
  File "/Users/iyadboustany/Desktop/lensmaster/Graphics/Scene.py", line 13, in <module>
    from OpenGL.GL import glGenBuffers, glBindBuffer, glBufferData, \
  File "/usr/local/lib/python3.8/site-packages/OpenGL/GL/__init__.py", line 3, in <module>
    from OpenGL import error as _error
  File "/usr/local/lib/python3.8/site-packages/OpenGL/error.py", line 12, in <module>
    from OpenGL import platform, _configflags
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/__init__.py", line 36, in <module>
    _load()
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/__init__.py", line 33, in _load
    plugin.install(globals())
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 97, in install
    namespace[ name ] = getattr(self,name,None)
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
    value = self.fget( obj )
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 62, in GetCurrentContext
    return self.CGL.CGLGetCurrentContext
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
    value = self.fget( obj )
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 45, in CGL
    def CGL(self): return self.GL
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
    value = self.fget( obj )
  File "/usr/local/lib/python3.8/site-packages/OpenGL/platform/darwin.py", line 41, in GL
    raise ImportError("Unable to load OpenGL library", *err.args)
ImportError: ('Unable to load OpenGL library', 'dlopen(OpenGL, 10): image not found', 'OpenGL', None)

Notes:

Running glxgears works just fine.
I'm running macOS Big Sur beta (20A5343i)
I'm using python 3.8.5
I installed opengl using pip: pip3 install PyOpenGL PyOpenGL_accelerate
Answer: This error is because Big Sur no longer has the OpenGL library nor other system libraries in standard locations in the file system and instead uses a cache.  PyOpenGL uses ctypes to try to locate the OpenGL library and it fails to find it.  Fixing ctypes in Python so that it will find the library is the subject of this pull request
https://github.com/python/cpython/pull/21241
So a future version of Python should resolve the problem.
To fix it now you can edit PyOpenGL file OpenGL/platform/ctypesloader.py changing line
    fullName = util.find_library( name )

to
    fullName = '/System/Library/Frameworks/OpenGL.framework/OpenGL'

Comment: Where is PyOpenGL located?
Comment: @JulianA. @yudhiesh @aeengineer you can find the file at this location `~/anaconda3/lib/python3.7/site-packages/OpenGL/platform/ctypesloader.py` or similar paths to your python installation
Comment: content of (base) [~/Downloads/resources]$ ls /System/Library/Frameworks/OpenGL.framework/
Libraries Resources Versions  , <- are these, and adding that file path did not help as there was no folder OpenGl in there
Comment: Yes how would I access the file?
Comment: How would I obtain the correct filepath for my specific case? Please advise
Comment: @TomGoddard --This was so helpful. Thanks!
Comment: hi i am having the same issue is there a fix for this on mac m1,
Comment: Python 3.10 fixes the whole mess.
Comment: BETTER USE `fullName = "/System/Library/Frameworks/{}.framework/{}".format(name,name)`
Answer: Since I hate the idea of patching a Python package (plus it is really hard to manage that with use of Conda to install said package), I offer this kludge as a workaround for until Python gets its Big Sur (aka Big Nuisance) update:
try:
    import OpenGL as ogl
    try:
        import OpenGL.GL   # this fails in <=2020 versions of Python on OS X 11.x
    except ImportError:
        print('Drat, patching for Big Sur')
        from ctypes import util
        orig_util_find_library = util.find_library
        def new_util_find_library( name ):
            res = orig_util_find_library( name )
            if res: return res
            return '/System/Library/Frameworks/'+name+'.framework/'+name
        util.find_library = new_util_find_library
except ImportError:
    pass

Answer: It's better to change this to
fullName = "/System/Library/Frameworks/{}.framework/{}".format(name,name)

otherwise GLUT won't work. At least, this let me run the Cozmo SDK's 3d stuff again.
Comment: Indeed fixed my problems.
Answer: FYI, in my case it was:
        fullName = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/OpenGL.framework/OpenGL'

Answer: None of these are really very suitable answers - there were several issues with both MacOS and pyOpenGL.
Fortunately, however - everything seems to be working at last if we upgrade to Python3.10 (or above)


Send a flag instead a letter based in a json

Question: i don't know if i expleined i receive a json from an odata call and i send it to my table but one field have a X or is empty but instead of showing a X i want to show a flag like in ObjectListItem with a ObjectMarker type="Flagged" and just showing the flag
my table: (i delete some colums for this but my field that i'm interested is Sucursalescolacion and Sucursalesflag)

                <columns>
                    <Column>
                        <Text text="{i18n>colSucursalesid}" />
                    </Column>
                    <Column>
                        <Text text="{i18n>colSucursalesnombre}" />
                    </Column>
                    <Column>
                        <Text text="{i18n>colSucursalesdircalle}" />
                    </Column>
                    <Column>
                        <Text text="{i18n>colSucursalesdirnumero}" />
                    </Column>

                </columns>
                <items>
                    <ColumnListItem press="" type="Active">
                        <Text text="{Sucursalesdepto}"/>
                        <Text text="{Sucursalesfono1}"/>
                        <Text text="{Sucursalesfono2}"/>
                        <Text text="{Sucursalesactiva}"/>
                        <Text text="{Sucursaleshoraini}"/>
                        <Text text="{Sucursaleshorafin}"/>

                        <Text text="{Sucursalescolacion}"/>

                        <Text text="{Sucursalesflag}"/>
                    </ColumnListItem>
                </items>

my controller

var bSucursales = this.byId("bSucursales");
         bSucursales.setVisible(true);
         oDataModel.read("/" + resultado2 +"?$filter=Maestropais eq '" + resultado + "'" + "and Maestrometodo eq '" + metodo + "'", {
          success: function(oData, response) {
           var oResults = oData.results;
                    oModel.setData(oResults);
                    bSucursales.setModel(oModel);
           },
           error: function(oError) {

           }
         });
Answer: You could use expression binding:
<ObjectMarker type="{= ${Sucursalesflag} === 'X' : 'Flagged' : ''}" />

More info: https://sapui5.hana.ondemand.com/#/topic/5cff8d1c3fb84c5db7a00f2daca125af
Answer: Also, you can choose to use a formatter as:

<ObjectMarker type="{path: 'Sucursalesflag', formatter: '.formatSalesFlag'}"/>

Define formatter function in your controller:

.
.
.
statusText: function (sSalesFlag) {
  if(sSalesFlag == 'X'){
        return 'Flagged';
      }
    else{
      return '';
    }
  }
}

You can write more complex custom formatters for different use-cases. Learn more about customer formatters here


How to scatter plot each group of a pandas DataFrame

Question: I am making a scatter plot with the geyser dataset from seaborn. I am coloring the points based on the 'kind' column but for some reason, the legend only shows 'long' but leaves out 'short'. I don't know what I am missing. I also was wondering if there is a simpler way to color code the data one that does not use a for-loop.
geyser_df.head()
     duration  waiting   kind
0       3.600       79   long
1       1.800       54  short
2       3.333       74   long
3       2.283       62  short
4       4.533       85   long

x = geyser_df['waiting']
y = geyser_df['duration']
col = []

for i in range(len(geyser_df)):
    if (geyser_df['kind'][i] == 'short'):
        col.append('MediumVioletRed')
    elif(geyser_df['kind'][i] == 'long'):
        col.append('Navy')

plt.scatter(x, y, c=col)
plt.legend(('long','short'))
plt.xlabel('Waiting')
plt.ylabel("Duration")
plt.suptitle("Waiting vs Duration")
plt.show()

Answer:
The correct way to do this with pandas is with pandas.DataFrame.groupby and pandas.DataFrame.plot.
Tested in python 3.8.12, pandas 1.3.4, matplotlib 3.4.3, seaborn 0.11.2

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# load data
df = sns.load_dataset('geyser')

# plot
fig, ax = plt.subplots(figsize=(6, 4))
colors = {'short': 'MediumVioletRed', 'long': 'Navy'}
for kind, data in df.groupby('kind'):
    data.plot(kind='scatter', x='waiting', y='duration', label=kind, color=colors[kind], ax=ax)

ax.set(xlabel='Waiting', ylabel='Duration')
fig.suptitle('Waiting vs Duration')
plt.show()

The easiest way is with seaborn, a high-level API for matplotlib, where hue is used to separate groups by color.

sns.scatterplot: an axes-level plot
sns.relplot: a figure-level plot where kind='scatter' is the default plot style

fig, ax = plt.subplots(figsize=(6, 4))
colors = {'short': 'MediumVioletRed', 'long': 'Navy'}
sns.scatterplot(data=df, x='waiting', y='duration', hue='kind', palette=colors, ax=ax)

ax.set(xlabel='Waiting', ylabel='Duration')
fig.suptitle('Waiting vs Duration')
plt.show()

colors = {'short': 'MediumVioletRed', 'long': 'Navy'}
p = sns.relplot(data=df, x='waiting', y='duration', hue='kind', palette=colors, height=4, aspect=1.5)

ax = p.axes.flat[0]  # extract the single subplot axes

ax.set(xlabel='Waiting', ylabel='Duration')
p.fig.suptitle('Waiting vs Duration', y=1.1)
plt.show()

Answer:  You're passing x = geyser_df ['waiting'] and y = geyser_df ['duration'] as a single dataset which causes plt.scatter to only use as label="long" as legend. I don't have enough experience using this type of libraries but to reproduce the example you describe you need to write a program like this:

long = [[], []]
short = [[], []]
col=['MediumVioletRed', 'Navy']

for i in range(len(geyser_df["kind"])):
  if (geyser_df["kind"][i] == "long"):
      long[0].append([geyser_df['waiting'][i]])
      long[1].append([geyser_df['duration'][i]])
  else:
      short[0].append([geyser_df['waiting'][i]])
      short[1].append([geyser_df['duration'][i]])

plt.scatter(long[0], long[1], c=col[1], label="long")
plt.scatter(short[0], short[1], c=col[0], label="short")

plt.legend()
plt.xlabel('Waiting')
plt.ylabel("Duration")
plt.suptitle("Waiting vs Duration")
plt.show()


Group array by values in php

Question: I have an array, which contains data as follows:
 Array (
[google.com] => Array
    (
        [youseo.com] => 1,
        [seo.com] => 1,
        [linkbuilding.com] => 0,
        [seo556.com] => 1,
    )

[youtube.com] => Array
    (
        [youseo.com] => 0,
        [seo.com] => 0,
        [linkbuilding.com] => 0,
        [seo556.com] => 1,
    )

[facebook.com] => Array
    (
        [youseo.com] => 0,
        [seo.com] => 1,
        [linkbuilding.com] => 1,
        [seo556.com] => 0,
    )
  )

And I need to populate new array and count value of url:
Array
 (
 [google.com] => 3
 [youtube.com] => 1
 [facebook.com] => 2
 )

Please any help for this?
Answer: You could use array_values and array_sum:
$counts = array();
foreach ($array as $page_name => $record)
    $counts[$page_name] = array_sum(array_values($record));

But that's assuming the values can only be 0 or 1.
Answer: If $a is your array:
$counts = array();
foreach ($a as $page_name => $page)
{
    foreach ($page as $name => $value)
    {
        $counts[$page_name] += $value;
    }
}

Answer: Just use array_map with array_sum
$result = array_map(function($el) {
    return array_sum($el);
}, $data);

Group array by values in php


Class template argument deduction ambiguity

Question: Is the following code example in compliance with the C++20 standard or should it be rejected due to an ambiguous deduction?
template<typename...>
struct s {
    s(int) requires true {}
    s(int) {}
};
static_assert(not noexcept(s{{}})); // clang nope, gcc ok, msvc ok

Live example

The error message from Clang:
<source>:6:28: error: ambiguous deduction for template arguments of 's'
    6 | static_assert(not noexcept(s{{}}));
      |                            ^
<source>:3:5: note: candidate function [with $0 = <>]
    3 |     s(int) requires true {}
      |     ^
<source>:4:5: note: candidate function [with $0 = <>]
    4 |     s(int) {}
      |     ^

As indicated by CWG Issue 2628 that Brian Bi linked in his answer, it appears that there currently is no wording in the C++20 standard that mandates the requires-clause of a constructor to be propagated to the implictly-generated deduction guide. As a workaround, it's possible to provide a user-defined deduction guide instead:
template<typename...>
requires true
s(int) -> s<>;

template<typename...>
s(int) -> s<>;

Note that for this particular code example, the deduction guide s(int) -> s<>; would also work, since a user-defined deduction guide is preferred over an implicitly generated one. It seems the consideration here would be quality of error-reporting opposed to less code bloat.
Comment: I think it is a clang bug.
Answer: This is CWG 2628: when the compiler forms the implicit deduction guide from the constructor s::s(int) requires true, that deduction guide should also have requires true, which makes it more constrained than the other deduction guide; but the wording currently doesn't specify that the deduction guide gets the constraint. It seems that GCC already does it, but Clang doesn't do it yet.
Comment: @303 I suspect they just chose the example where they discovered the issue, rather than the simplest possible example that illustrates the issue. I think you're right that the example is incorrect. I will let CWG know.
Comment: Regarding CWG 2628, do you happen to know why they choose for this rather convoluted example? Also, I don't see how the example provided actually causes an ambiguity, as stated by [cppreference](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction): *"A function template generated from a user-defined deduction guide is preferred over one implicitly generated from a constructor or constructor template."*


Replace url of background-image with the url of a clicked image with jQuery

Question: When any image in an unordered list is clicked, I would like the url associated with the thumbnail to replace the background-image css value of a particular div. Say,

When dog_thumb.jpg is clicked, the href attached to it gets put into the css of the div:

If cat_thumb.jpg was then clicked, its href would switch with the div's background-image value.
Obviously, I won't use inline styles for the final page. I know how to switch the src of a thumbnail with that of another image on the page or switch between whole classes but, I can't seem to be able to find a way to manipulate just one attribute of a single class. I would like to do it this way because switching the background-image is much easier than having a bunch of divs on top of each other with z-indexes.
Answer:    $('img').click(
        function (){
            $(this).parent('ul').next('div').css('background', $(this).attr('src'));
        }
   )

Also as @RichardNeilIlagan suggested,
   $('img').click(
        function (){
            $('div#background').css('background', $(this).attr('src'));
        }
   )

Comment: Why not just go directly to `$('div#background')`?
Comment: @RichardNeilIlagan well, i guess he might have many such `div` s after many list, so i put up general solution.
Answer: You click the anchor, and you want that href to replace the #background? Based on your example:
// all links will work this way, based on your example
$('a').click(function(e){
    // replace the css background image with the one in the href
    // please note, this assumes the href is the absolute or relative URL to the image
    $('#background').css('backgroundImage', $(this).attr('href'));
    // stop the link from acting like a link
    e.preventDefault();
});

You could also take the img src ad strip the thumb from it and put it in to the #background, you could also put a series of classes in your CSS and add/remove the class name as necessary to change the background. (I would recommend "default" as a class to add the default image, versus leaving it inline).
JavaScript manipulation inline CSS should overwrite the default styling you have (so if default.jpg is tied to the ID, it should overwrite it).


What would cause this error when upgrading Panels module?

Question: <code>$ drush up panels
Code updates will be made to the following projects: Panels [panels-7.x-3.4]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project panels was updated successfully. Installed version is now 7.x-3.4.
Backups were saved into the directory /home/bzisad0/drush-backups/newco/20140724235906/modules/panels.       [ok]
WD php: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't [error]
exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of
/var/www/vhosts/www.companyname.com/releases/20131007153705/includes/cache.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of /var/www/vhosts/www.companyname.com/releases/20131007153705/includes/cache.inc).
Drush command terminated abnormally due to an unrecoverable error.                                           [error]
Backups were restored successfully.                                                                          [ok]
</code>
The only clue I have is that the company I'm doing work for underwent a merger, and we had to set up the new web site before the name of the new company was public, so everything went by "newco".  I could not find anywhere that this is configured in Drupal, but I see that showing up in the error message "Base table or view not found: 'newco.cache_panels' doesn't exist".
I'm not sure if that's relevant or not, but I'm mentioning it just in case, and hoping it's not a red herring.
Answer: For some reason, the "cache_panels" table of panel used for cache is missing.
It's reported as an issue for this module.
To solve this error, first, I strongly recommend to do a backup of the database before make any change (even before do a drush updb or update a specific module as you are trying in this case).
You cloud try one of the following solutions:

Using drush, follow this proposed solution.
Using a SQL query, follow this other solution.

I recommend you to use the first alternative as I see that you use drush.


iptables doesn't log anything

Question: I'm trying to defend my server (Ubuntu Lucid 10.04) from some brute force ssh attacks by configuring the iptables.
I want to log the matches to DROP rules, but it wasn't working, so I tried the very basic:
iptables -A INPUT -p tcp --dport 22 -j LOG --log-level info --log-prefix "TEST: "

But it doesn't log anything! I tried changing the log-level: debug or 7 and adding
kern.=debug     -/var/log/firewall to /etc/syslog.conf but nothing gets written to/var/log/messages or /var/log/firewall
The rule does get some matches:
$ iptables -L -v
pkts bytes target     prot opt in     out     source               destination
44  5543 LOG        tcp  --  any    any     anywhere             anywhere            tcp dpt:ssh LOG level debug prefix `TEST: '

iptables logging not working has a solution to update rsyslog to a newer version. However according to this source "this solution is messing with the default logging system"
Does anybody know a better solution?
If not, I could try updating rsyslog (compile from source), but how can I revert to the default rsyslog if it messes things up?
EDIT:  rsyslog drops it's privileges, so it can't read /proc/kmesg. This should be solved in newer kernels but unfortunately, I'm stuck on 2.6.18.
"the fact it doesn't read kmsg on older kernels is DELIBERATE
and will not be fixed."
I tried to let rsyslog keep it's root privileges, by altering /etc/rsyslogd.conf
$PrivDropToUser root
$PrivDropToGroup root

But that doesn't work either, which confuses me. Why can't this root process read a file root owns?
Comment: If you switch your rule to just `iptables -A INPUT -p tcp -j LOG` do you see any logging?
Comment: Nope, nothing. All messages do show up in `$ dmesg` though
Comment: What version of rsyslog are you running? When I added the above rule into a default Debian stable system, it logged to kern.log as expected (using rsyslog 4.6.4-2).
Comment: rsyslogd 4.2.0-2ubuntu8, Ubuntu 10.04 2.6.18-028stab089.1. `/var/log/kern.log`  shows `kernel: imklog: Cannot read proc file system, 1.`
Answer: You could install fail2ban and configure the ssh jail to automatically ban the IP addresses that are attacking your server based on the messages that sshd puts in the logs. This is a fairly standard way of doing what you want.
If you haven't already done so you should disable root logins via ssh as well as enabling and using key based authentication.
Comment: The iptables config works, just the logging doesn't, so I don't really need another third-party package. Root login is disabled and key authentication is required of course ;)
Answer: You're setting log-level info, but, your syslog config is outputting log-level debug. Either change syslog to output kern.info or your iptables rule to output to log-level debug to match your ruleset config.
Comment: I tried that already, but by default it should write to /var/log/messages (without the kern.=debug). Doesn't work unfortunately..

iptables doesn't log anything


Excel filter calendar values from data

Question: Attached screenshot has data which is A11:C17 and week calendar B4:H6. I want to match calendar dates from data and showing all activities for that date to calendar cells. For sample, I have put manually E6,F6 and G6 but I want to know how to achieve using excel scripts ie. match the calendar date to data table and concatenate all activities to calendar cell next to date.
Thanks
Answer: Use TEXTJOIN() as an array formula:
<code>=TEXTJOIN(CHAR(10),TRUE,IF($C$11:$C$16 = C$4,$B$11:$B$16,""))
</code>
Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.
TEXTJOIN was introduced with a subscription to Office 365 Excel.

Excel filter calendar values from data


Fair Coin Testing (combine the results or not)

Question: Let's assume that you saw your cousin flipping the coin 20 times and he got 12 heads and 8 tails. You see your cousin flipping the coin 20 more times and want to test if the coin is fair or not.
Let's consider the following two cases:
1) the cousin flipped the coin 20 times (didn't care how many heads or tails come up)
2) the cousin flipped the coin UNTIL he sees at least 4 more heads than tails or 4 more tails than heads, and that number came out to be 20 flips.
In each of these two cases, how would you test it? Would you combine the results from the next 20 coin flips that your cousin does or ignore the previous flips and just consider the next 20 flips?
Any reference would be greatly appreciated.
Comment: See https://en.wikipedia.org/wiki/Likelihood_principle
Comment: This sounds like a Silicon Valley interview question. In case (1), the number of heads (or tails) would follow the Binomial(n=20, p) distribution. If you use the Binomial p.m.f. with k = 12 and solve for p, shouldn't you expect to end up with ~0.5? (not sure how that would prove anything though unless n was much bigger). Case (2) would be the same approach using the negative Binomial p.m.f. (There's also a chance that I'm completely off).
Comment: Was it seeing the outcome of the first set of flips that made you decide to test for fairness? The wording sort of suggests it, and knowing whether that's the case is important to a good answer.
Comment: @Digio I believe for case 2 the PMF would be a hitting-time distribution rather than a negative-binomial. See my answer.
Comment: I don't follow - how would you test what, exactly?
Comment: @Glen_b  Could you explain to me how that is important?
Comment: @Glen_b I didn't even think that would be important. If so, I would like to know how that affects the hypothesis testing in each case.
Comment: Converted comments to an answer (at least it answers part of the question if the premise holds)
Answer: [Since this doesn't deal with the main two questions (it relates more to their  premises - answering the subsequent question in the body text), this is perhaps only a partial answer. Someone trying to answer 1 and 2 would presumably need to make the assumption that (in spite of the wording) the desire to test did not come from observing the first set of flips to deal with the numbered questions. In part I see the problem with the phrasing of the setup and the numbered questions as focusing on the details of estimating probability while ignoring the larger issue relating to severe bias, making the apparent distinction in the two cases largely beside the point.]
In short, I focus here on "Would you combine the results from the next 20 coin flips that your cousin does or ignore the previous flips and just consider the next 20 flips?" and I discuss it in detail as requested -- indeed, it's easily the most critical part here, and the part that's very widely misunderstood, occasionally even among statisticians. All those "my third cousin's birthday is the same day as my girlfriend and they were born in the same year in the same town, what are the chances??" questions are examples of this sort of problem, yet at the same time, it affects a lot of published work (that is, where the observed data impact the hypothesis tested).

If the desire to test the hypothesis is created by seeing the outcome of the first set of flips you shouldn't include them in your test -- the wording of the question suggests it. That's a data-generated hypothesis
Otherwise you bias your p-values downward; you'll be much more likely to reject nulls than you should be when there's nothing going on.
Let's take a slightly more extreme case to make the point more clearly.
Imagine 100,000 people all toss (fair) coins 20 times. The ones that get very high (18+) or low numbers (0-2) of heads (we expect around 20 of each) decide to test those coins and the ones that got middling numbers do not.
The ones that do test combine their first 20 tosses with another 20 tosses and test at the 5% level. What's the probability that they reject the null?
(NB if the test works as it should, given they have a fair coin in this setup, it should be 5%... but it's waay bigger). That's what testing hypotheses suggested by the data do.
I just did it in simulation and got 42 people (who decide to test), and of those 32 of them went on to reject the null after combining their data. This is when the coin is fair! (larger simulations give similar results)
Test on the second set (i.e. data collected after the first set made you want to test the hypothesis) & you're okay.
Comment: (+1) Good point! I tried to explore your final suggestion further in my own answer ... hopefully it is coherent :)
Answer: The answer by Glen_b does a good job highlighting the possible dangers of combining the two data sets to test coin fairness (i.e. if performing the second experiment was contingent on the first one's results).
Here I consider how to test under the alternative experimental conditions, assuming we use only the second data set. That is, given the data of $N=20$ flips with $K=12$ heads, generated either by

fixing $N=20$ ahead of time
flipping until the difference between heads/tails is $m=4$ (fixed ahead of time)

how consistent is the data with a fair coin?
In the fixed $N$ case, the number of heads $k$ is binomial distributed
$$\Pr\big[k\big] = \mathrm{Binom}_{N,p}\big(\,k\,\big)$$
where $k=0,1,\ldots,N$. Under the null hypothesis of $p=\tfrac{1}{2}$, the expected number of heads is $\langle{k}\rangle=10$, and the exceedance probability of the data is $\Pr\big[|k-\langle{k}\rangle|\geq|K-\langle{k}\rangle|\big]=50\%$.
In the fixed  $m$ case, the number of flips $n$ is now a random variable, known as the hitting time. Under the null hypothesis the head/tails difference is an unbiased simple random walk, with hitting time distribution
$$\Pr\big[n\big] = \tfrac{m}{n}\,\mathrm{Binom}_{n,p}\big(\,\tfrac{n+m}{2}\,\big)$$
where $n=m,m+2,\ldots,\infty$. For a biased coin the hitting time will be shorter (since the boundaries $\pm{m}$ are symmetric). So we can measure consistency as $\Pr\big[n\leq{N}\big]=38\%$ under the null.
So for the same data, produced by different experimental setups, give slightly different p values.

A few  notes:

The second setup does not follow a negative binomial distribution (this would require fixing $m$ heads, rather than excess heads).
Probably the first and second data sets could be combined to compute a consistent Bayesian posterior for $p$. In the case of a fixed-$N$ second experiment, the number of heads and tails could then literally be combined. For the fixed-$m$ second experiment, things are more complicated (e.g. for $p\neq\frac{1}{2}$ the $+m$ vs. $-m$ cases would differ and must be averaged together to get the total likelihood).


Como passar vários parâmetros pra query no mongoose?

Question: Estou querendo fazer uma busca no Mongodb com Mongoose (NodeJs), onde eu quero os objetos cujo atributo url que é uma string contenha dentro de si pelo menos 1 dos valores que eu tenho num array. Como eu poderia fazer isso, usando apenas 1 find()?
Por exemplo:
Objeto salvo no Mongo:
{url:"www.site.com.br/?laranja?...}
const chavesDeBusca = [laranja, melancia]
const query =  model.find({url: 1 ou mais valore de chavesDeBusca})

Obviamente esse código acima não funciona, mas a ideia é fazer isso.
Eu poderia usar uma regex como valor da chaveDeBusca.
Mas não estou conseguindo montar uma que faça isso. Por exemplo:essa regex faria o seguinte:  "dá match se uma string contém  um ou mais elementos contidos no array chaveDeBusca"
Será que o '$in' resolve? Aparentemente não, pois o resultado da busca vem vazio, mesmo depois de eu dar exec()
Ideias?
Answer: Pode usar o operador $in.
const chavesDeBusca = ['laranja', 'melancia']
// cria a query
const query = model.find({ 'atributo': {'$in' : chavesDeBusca } })

// resolver os resultados utilizando then
query.then((error, documents)=> {
    if (error) {
        return console.log(erro)
    }
    // resultados iteraveis em documents
})

// resolver os resultados usando await exec()
// o await tem que estar contido em uma async function
const documents = await query.exec();
// espera pelos resultados e executa a proxima linha
console.log(documents)

Edit:
Use o operador $or
const chavesDeBusca = ['laranja', 'melancia']

// mapear o array de busca para `$or`
const chavesDeBuscaMapeado = chavesDeBusca.map(chave => ({
    'atributo' : new RegExp(`.*${chave}.*`, 'ig')
}))
// cria a query
const query = model.find({ '$or' : chavesDeBuscaMapeado })

Comment: To testando aqui. Mas pra quer serve esse exec()? Eu li na documentação mas não tá claro. O .find() já não retorna os objetos resultantes da query?
Comment: @LucasPletsch Eu uso muito promises o `exec` ira retornar uma `Promise`, pode correr a query de tal foma `const query = await mode.find(...).exec()` dentro de uma funcão `async`
Comment: se eu não boto o exec, então a chamada ao método find() bloqueia a execução do meu programa? Ou seja, é feita de forma síncrona?
Comment: @LucasPletsch nao o `find` nao bloqueia, qualquer das chamadas retorna um `thenable` apenas o `exec` retorna uma `Promise` verdadeira. depende da arquitetura do seu projeto. Eu perfiro usar `Promises` :)
Comment: @LucasPletsch E bem possivel para queries mais complexas ou com muitos resultados, Eu recomendo usar `await`  `exec`. Irei atualizar a minha resposta com mais detalhes.
Comment: Ah. Eu me confundo com await. Mas posso fazer simplesmente model.find().then((err, docs) =>{ faz algo com os docs  } também né
Comment: @LucasPletsch Perfeitamente! qualquer das formas esta correta! :) atualizei a resposta com mais detalhes
Comment: Então se eu faço simplesmente   const query =  model.find({ 'atributo': {'$in' : chavesDeBusca } })   e tento acessar essa constante query na  linha imediatamente abaixo, ela pode estar vazia, ou ainda sem o resultado da busca?
Comment: Ao dar console.log(documents) não imprime nada, aí eu dei um console.log(typeof documents) e disse que era um object. Aí eu dei um Object.values(documents) e também não imprimiu nada. Mas porque não tem nada dentro? Minha busca deu errado?
Comment: Na verdade assim. O valor do atributo no banco de dados é uma url no formato de string. Então, o valor do atributo inteiroo nunca vai ser "Laranja". Mas pode ser www.google.com/laranja/suco, por exemplo. O '$in' ainda retornaria esse objeto?
Comment: Vou alterar a pergunta
Comment: Se o valor no banco de dados não é exatamente o valor de busca de facto essa query retorna um objeto vazio, pode entao usar o operador `$or` mapeando o array de pesquisa, vou atualizar a resposta com mais detalhes


How to get that string noise buildup effect on guitar?

Question: In a TON of hard rock songs, there is a distinctive swell of screechy string noise during a brief break in the music to create a sense of power and explosion before the music resumes at high intensity.
How can I get this buildup sound?
For example, at 0:55 in this song the effect I am describing is used:
Answer: Quite a bit of that effect can be accomplished by utilizing a high gain guitar amp, cranking it up and then compressing it with a good studio grade compressor. This results in things like string noise being amplified up while maintaining some control over the overall level. This type of sound was not really desired in other styles of music, but in rock, it seemed to demonstrate power and brute force.
Comment: This is helpful for getting the sound overall, but I'm speakiing specifically of how to get it when you want it quickly.
Comment: You start with a high gain amp, an old tube Marshall or similar to get that crunch, come out of the axe into a stomp box compressor,  and push everything till you get what you 're looking for. Experimentation often leads to answers. However I stand by my original answer as how it was accomplished in the studio.