Extracting string from line, give as input to a command and then output the entire line with replacing the string

Question:
I have a file containing like below, multiple rows are there
test1| 1234 | test2 | test3

Extract second column 1234 and run a command feeding that as input
lets say we get X as output to the command
Print the output as below for each of the line
test1 | X | test2 | test3

Prefer if I could do it in one-liner, but open to ideas.
I am able to extract string using awk, but I am not sure how I can still preserve the initial output and replace it in the output. Below is what I tested
cat file.txt | awk -F '|' '{newVar=system("command "$2); print newVar $4}'

#

Sample command output, where we extract the "name"
openstack show 36a6c06e-5e97-4a53-bb42
+----------------------------+-----------------------------------+
| Property                   | Value                             |
+----------------------------+-----------------------------------+
| id                         | 36a6c06e-5e97-4a53-bb42           |
| name                       | testVM1                           |
+----------------------------+-----------------------------------+

Comment: You should stop worrying about getting a "one liner" and instead just focus on getting a solution that's concise, robust, efficient, portable, etc. - i.e. satisfies all the criteria that actually matter for good software. The right solution depends on how large your input file is, how important speed of execution is, and whether `command` can take a whole list of values at once and produce the corresponding list of converted values, or if it's required to operate on 1 value at a time. So please provide more information in your question and give a concrete example of `command` so we can help.
Comment: In short, you want to replace 1234 on each line with the output of a command?
Comment: Yes, Can that be easily done on one liner while I print the content output ?
Comment: @RavinderSingh13 - I would prefer to run it by two commands, I know its possible with your option, but I see you created a separate script
Comment: @sshark, Actually it is NOT a single script, it is multiple commands; you could see them in steps  information.
Answer: Perl to the rescue!
perl -lF'/\|/' -ne 'chomp( $F[1] = qx{ command $F[1] }); print join "|", @F' < file.txt

-n reads the input line by line
-l removes newlines from input and adds them to prints
F specifies how to split each input line into the @F array
$F[1] corresponds to the second column, we replace it with the output of the command
chomp removes the trailing newline from the command output
join glues the array back to one line
Answer: Using awk:
awk -F ' *| *' '{("command "$2) | getline $2}1' file.txt

e.g.
$ awk -F ' *| *' '{("date -d @"$2) | getline $2}1' file.txt
test1| Thu 01 Jan 1970 05:50:34 AM IST | test2 | test3

I changed the field separator from | to *| * to accommodate the spaces surrounding the fields. You can remove those based on your actual input.
Answer: If command can take the whole list of values once and generate the converted list as output (e.g. tr 'a-z' 'A-Z') then you'd want to do something like this to avoid spawning a shell once per input line (which is extremely slow):
awk -F' *[|] *' '{print $2}' file |
command |
awk -F' *[|] *' -v OFS=' | ' 'NR==FNR{a[FNR]=$0; next} {$2=a[FNR]} 1' - file

otherwise if command needs to be called with one value at a time (e.g. echo) or you just don't care about execution speed then you'd do:
awk -F' *[|] *' -v OFS=' | ' '{
    cmd = "command \047" $2 "\047"
    if ( (cmd | getline line) > 0 ) {
        $2 = line
    }
    close(cmd)
    print
}' file

The \047s will produce single quotes around $2 when it's passed to command and so shield it from shell interpretation (see https://mywiki.wooledge.org/Quotes) and the test on the result of getline will protect you from silently overwriting the current $2 with the output of an earlier command execution in the event of a failure (see http://awk.freeshell.org/AllAboutGetline). The close() ensures that you don't end up with a "too many open files" error or other cryptic problem if the pipe isn't being closed properly, e.g. if command is generating multiple lines and you're just reading the first one.

Given your comment below, if you're going with the 2nd approach above then you'd write something like:
awk -F' *[|] *' -v OFS=' | ' '{
    cmd = "openstack show \047" $2 "\047"
    while ( (cmd | getline line) > 0 ) {
        split(line,flds)
        if ( flds[2] == "name" ) {
            $2 = flds[3]
            break
        }
    }
    close(cmd)
    print
}' file

Comment: Thanks everyone for the help, If I have my "command" having its own operations of awk. Example below command=openstack show  | grep name | awk -F "|" '{print $3}'       Is it possible to use it within the awk block you defined above ?
Comment: Yes but it'd be the wrong thing to do. Let's assume `` in your comment is `$2` in the scripts disussed so far then you wouldnt embedd `openstack show  | grep name | awk -F "|" '{print $3}'` within an awk script since `grep name | awk -F "|" '{print $3}'` is **shell** code, instead you'd set `cmd` above as `cmd="openstack show \047" $2 "\047"` and then write **awk** code to parse its output that getline reads into `line`.
Comment: I updated my answer to show a possible solution but I don't know anything about how `openstack` is called nor what it outputs so I'm guessing at the right approach.
Comment: Revised awk works well, flds[3] contains lot of spaces. Is there a way to trim it ?
Comment: Of course, it's only software, but all i had to go on was the command line you said worked for you and so what I wrote does just that same thing. I can't keep guessing at what we're trying to parse though - please edit your question to include examples of the command you're trying to execute (`openstack show `) and the output of that command and what you want to extract from that output to use in place of `$2` in the input file.
Comment: You can't put formatted text in a comment, See my previous comment and update your question
Answer: This finally did the trick..
awk -F' *[|] *' -v OFS=' | ' '{
    cmd = "openstack show \047" $2 "\047"
    while ( (cmd | getline line) > 0 ) {
        if ( line ~ /name/ ) {
            split(line,flds,/ *[|] */)
            $2 = flds[3]
            break
        }
    }
    close(cmd)
    print
}' file


verificar input vazia

Question: Tenho uma input text e quero verificar se o valor está vazio. No meu exemplo tenho isto:
var qttDeclared = tr.getElement("input[name$='[qttDeclared]']").get("value").toInt()
if(qttDeclared == "") {
        console.log("vazio");
    }

Mas isto não me está a funcionar.
Answer: Dá-me ideia que estás a usar MooTools... é o caso?
De qq maneira, com essa API podes fazer isso assim:
var qttDeclared = tr.getElement("input[name$='[qttDeclared]']").get("value").trim();
if(qttDeclared === "") {
    console.log("vazio");
}

Ou seja, o .get('value') vai-te dar uma string e o .trim() remove os espaços vazios, daí que se estiver vazia vai sobrar só "".
Comment: Reparei que há um voto negativo na minha resposta. Um comentário é bem-vindo, não levo a mal se houver coisas a melhorar na resposta.

verificar input vazia


How to master lengthy Tatum-style runs when I hit a wall?

Question: I've been trying to master a certain pattern for my improv that I like to call the Tatum-style descending pentatonic scale. Jazz greats like Tatum would often break into this extremely rapid descending pentatonic scale pattern that would end on the downbeat with the root of the next chord.
For instance when moving from an FM9 to Bb7, they would perhaps finish the FM9 measure with a descending A G E D C A G E D C pattern, starting way in the top octaves and running down the length of the piano, ending on the downbeat of the next measure on a Bb.  Hopefully you all can make sense of what I'm talking about, it's a common jazz improv pattern.
My problem is that when I attempt to play these at tempo, I go fine for a couple octaves' worth, but then halfway down the piano I lose the pattern.  I've tried practicing at slow tempo, even breaking it down into achievable sizes like only one octave, then two octaves, then three octaves of the pattern, etc.  But try as I might, with all the practice, when it comes to doing the full run at tempo, it always collapses about midway.
I can do it slowly, and I can do it at tempo in small sections, like two or three octaves, but for the full pattern, it's like my fingers get ahead of my brain (or maybe vice versa) and I just can't nail it.
Any suggestions? Do I just need to keep practicing? Is there something mentally I can do to keep my brain and fingers on the same page? Is there something technically that will help with accuracy?
Thanks in advance for any help you can give!
Answer: Practice doens't make perfect.  Perfect ergonomic practice makes perfect. You can practice everything slowly but still be playing incorrectly.  Once you hard wire improper movement into the brain, it is there forever. Or, very difficult to undo.
It sounds like you were probably taught to cross the thumb under the palm.  This is an incoordinate movement.  I can't explain it here but when descending after you play the thumb, your elbow rises a bit, the arm shifts over and you supinate the the next fingers down.  This is what Art did.  What his elbow, not his hands.  There are not many videos of him so watch Oscar Peterson or Adam Makowicz.  Don't look at their hands but elbows.
Another thing that can get in the way of those runs are abducting and flexing at the same time.  When you abduct and flex simultaneously, you have two muscles pulling one bone in two directions and that will hinder your playing. Like a three legged race, both racers must move in the same direction at the same time or there will be pulls which will cause them to stumble.
Most of Art's playing came from his supinator and pronator muscles and of course, he depressed the keys with the weight of his arm.
Answer: I practice these kind of patterns by using different rhythms and a metronome.
I usually get the best results by using a rhythmic pattern which does not have the same length as the note pattern, so that you get inversions and don't always get on the same finger.
In this 5-note pattern, I suggest using one 8th note + two 16h notes or two 16th followed by one 8th. Start with a slow metronome and move up. The pause after the 8th not gives you time to think ahead and to place your fingers correctly.


Existence of differentiable matrix maps $M(3,\mathbb{R}) \rightarrow M(3,\mathbb{R})$

Question: Let's say that $M(3,\mathbb{R})$ is the set of square matrices of dimension $3*3$. Is there a neighborhood $N$ of $I_3$ on which there is a differentiable square root map $f: N \rightarrow M(3,\mathbb{R})$, with $$f(I) = \begin{pmatrix} -1 &0 &0 \\ 0 &1 &0\\ 0&0&1 \end{pmatrix}$$ and $(f(A))^2=A$ for every $A \in N$?
Another question is as follows:
Is there a neighborhood $L$ of $I_3$ on which there is a $C'$ class function $g: L \rightarrow M(3,\mathbb{R})$, with $$g(I) = \begin{pmatrix} 0 &1 &0 \\ 0 &0 &1\\ 1&0&0 \end{pmatrix}$$ and $(g(B))^3=B$ for every $B \in L$?
Background: I learned that matrices can represent derivatives of multivariable functions, and have understood, for example, Is there a general form for the derivative of a matrix to a power?, but I do now know how to use the conditions given by the question to answer if the questions are true or false.
edit: There is a previous possibly related question, that the Linear transformation $T: M(3,\mathbb{R}) \rightarrow M(3,\mathbb{R}), T(B) = AB+BA$ (for a diagonal $A \in M(3,\mathbb{R})$) is invertible if the diagonal elements of $A$ satisfy a certain condition.
Comment: I don't understand your similar question, what does $g$ have to do with $f$? As defined $I≠ g(I)^2 ≠ g(I) $ so I can't make a correct guess
Comment: I meant that the problems were of similar flavor sorry for the confusion. Will edit
Comment: looks the same after your edit?
Comment: Oops! Sorry now it's OK
Answer: We use the implicit function theorem, that is a well-known method.
i) for$f$. Let $p:X\in M_3\mapsto X^2$ and $U=diag(-1,1,1)$; then $p(U)=I_3$; the derivative of $p$ is
$Dp_X:H\in M_3\mapsto XH+HX$ and $Dp_U(H)=UH+HU$ is a sum of functions that commute.
$p$ has a local $C^{1}$ inverse from a neighborhood of $I_3$ to a neighborhood of $U$ IFF $Dp_U$ is invertible. Let $spectrum(U)=(\lambda_i)_i$.
According to
https://en.wikipedia.org/wiki/Kronecker_product#Abstract_properties
$spectrum(Dp_U)=\{\lambda_i+\lambda_j;i,j\}=\{-2,0,0,0,0,2,2,2,2\}$ and, therefore $p$ has no $C^1$ local inverse.
ii) for $g$ (in the same way).  Let $q:X\in M_3\mapsto X^3$ and $V=\begin{pmatrix}0&1&0\\0&0&1\\1&0&0\end{pmatrix}$; then $q(V)=I_3$; the derivative of $q$ is
$Dq_X:H\in M_3\mapsto HX^2+XHX+X^2H$ and $Dq_V(H)=HV^2+VHV+V^2H$ is a sum of functions that commute.
$spectrum(V)=spectrum(V^2)=(\mu_i)_i=\{1,u,u^2\}$ where $u=e^{2i\pi/3}$.
Then $spectrum(Dq_V)=\{\mu_i^2+\mu_i\mu_j+\mu_j^2;i,j\}$.
With $\mu_i=1,\mu_j=u$, we obtain (at least) one zero eigenvalue and, therefore, $q$ admits no local $C^1$ inverse.
EDIT. Answer to the OP and Sally G.
If you don't know the theory of Kronecker products, then, no matter, it suffices to display elements of $\ker(Dp_U)$ and of $\ker(Dq_V)$. For example
$H=\begin{pmatrix}0&0&0\\1&0&0\\0&0&0\end{pmatrix}\in\ker(Dp_U)$ and $H=diag(1,0,-1)\in\ker(Dq_V)$.
Comment: I lost you at spectrum. I went to your wiki link, but didn't find any information about adding eigenvalues. I'm not familiar with the Kronecker product, and I can't see how $spec(D_{pu})$ was calculated. Is this the only way to see that there is no local inverse?
Comment: You could also calculate a representation matrix of $\mathrm Dp(U)$ using the $3\times3$-matrices with a single 1 as an entry as a basis. You'd get a $9\times9$-matrix (since $M_3$ is a 9-dimensional space), which you can test for invertibility.
Comment: @Vercassivelaunos , yes it's standard. Yet, I try never to use this presentation because it suggests that the resolution of $AX+XB^T=(A\otimes I+I\otimes B)X=C$ is in $O(n^6)$ while there are methods that solve this equation with complexity $≈20n^3$.
Comment: I wrote this in answer to @SallyG, who asked for a different approach. It wasn't meant to criticize your way. I should have @ them to be more clear.
Comment: @Vercassivelaunos , you did well.
Answer: I'm not entirely sure about differentiable maps in general, but to test for the existence of a $C^1$-map, you can use the inverse function theorem: you're looking for a local inverse of the $C^1$-map $h:M(3,\mathbb R)\to M(3,\mathbb R),~A\mapsto A^2$ around $A_0$, where $A_0$ is one of the matrices above. Such a map exists iff $\mathrm Dh(A_0)$ is invertible. So you should test for that.
Comment: i downvoted. this shud be a comment
Comment: Sorry. Is it because it only covers a special case, or because it leaves the work of doing the actual computations to the asker?
Comment: It's because it's a comment and not an answer to the OP's question.
Comment: ok, sorry, I didn't really read the question or your answer. it just seemed like a comment, especially after you commented "it only covers a special case". but ill remove my downvote (and upvote since you've been nice)
Comment: I'll rephrase my question: what would I have to add to make it an answer as opposed to a comment? I gave an equivalent condition that's trivial (though tedious) to check. Would actually doing the check for op have been sufficient to make it an answer?
Comment: I thought you only dealt with a special case.
Comment: Kind of. Verbatim, they asked for a square root map. No restrictions on wether it's differentiable. The title implies that they want it to be differentiable. But the standard question in real analysis would be about $C^1$ functions. I assumed the latter of the three, without which this method won't work, so I added that as a caveat at the beginning, because I wasn't sure wether that was actually what they wanted. If such assumptions are not up to the community's standards, I'm fine with that. But I'd like to know if that's actually the issue, and not something else.
Comment: I'm so sorry. I need a differentiable square root map. Added it into the question, completely my fault for not saying it before!


How to limit "drush pm-updatestatus" to check only given project?

Question: When I run the drush pm-updatestatus drupal it keeps checking all other projects like:
drush pm-updatestatus drupal
Checking available update data ...                                                                                [ok]
Checking available update data for Drupal.                                                                                [ok]
Checking available update data for Views Bulk Operations (views_bulk_operations).                                                   [ok]
Checking available update data for AddThis (addthis).                                                                               [ok]
Checking available update data for Administration views (admin_views).                                                              [ok]
Checking available update data for BeautyTips API (beautytips).                                                                     [ok]
Checking available update data for BUEditor (bueditor).
Checking available update data for Date (date).                                                                                [ok]
Checking available update data for @font-your-face (fontyourface).                                                                  [ok]
Checking available update data for Entity API (entity).                                                                             [ok]
Checking available update data for FAQ Field (faqfield).                                                                            [ok]
Checking available update data for Features (features).                                                                             [ok]
Checking available update data for Feeds (feeds).                                                                                [ok]
Checking available update data for File Entity (file_entity).                                                                       [ok]
Checking available update data for File Field Sources (filefield_sources).                                                          [ok]
Checking available update data for Google reCAPTCHA (google_recaptcha).                                                             [ok]
Checking available update data for Gravatar (gravatar).                                                                             [ok]
Checking available update data for Insert (insert).                                                                                [ok]
Checking available update data for Job Scheduler (job_scheduler).                                                                   [ok]
Checking available update data for jQuery Update (jquery_update).                                                                   [ok]
Checking available update data for Libraries (libraries).                                                                           [ok]
Checking available update data for Mailhandler (mailhandler).                                                                       [ok]
Checking available update data for Mail System (mailsystem).                                                                        [ok]
Checking available update data for Media (media).                                                                                [ok]
Checking available update data for Memcache (memcache).                                                                             [ok]
Checking available update data for Metatag (metatag).                                                                               [ok]
Checking available update data for Mime Mail (mimemail).                                                                            [ok]
Checking available update data for MultiBlock (multiblock).                                                                         [ok]
Checking available update data for OAuth (oauth).                                                                                [ok]
Checking available update data for Extended Path Aliases (path_alias_xt).                                                           [ok]
Checking available update data for Pathauto (pathauto).                                                                             [ok]

Is there an alternative to drush pm-updatestatus or a way to make it check only the given project?
Answer: Since drush pm-updatestatus is so noisy, the "Checking available update data" output is IMHO debug output that shouldn't be displayed, I often use drush pm-releases (rl) in stead. The drawback with using drush rl is that it always produces output - you need to read, and optionally check that "Installed" and "Recommended" is on the same line.
Another work-around is to throw away the debug output:
drush pm-updatestatus MODULE 2> /dev/null


Applying a Synth Look and Feel to Sliders?

Question: I have a bunch of sliders that I am trying to apply a custom thumb to. The dimensions of it are 12x20, and I am applying it using a synth look and feel with the code below. This displays the thumb correctly for horizontal sliders, but once I make a vertical one the thumb gets distorted on the edges. Is there any better way to do this? Also, The thumb pressed code doesn't do anything, I would assume the reason for that is that sliderThumbs don't have a "pressed state"? Is there a way to make the L&F change on a slider when it is pressed? Thanks beforehand!!!
Cheers,
Lukas
<code><!-- Make and Bind a SliderThumb style -->
<style id="sliderStyle">

    <state>
      <property key="Slider.paintValue" type="boolean" value="false"/>
      <property key="Slider.thumbWidth" type="integer" value="12"/>
      <property key="Slider.thumbHeight" type="integer" value="21"/>
    </state>

</style>

<bind style="sliderStyle" type="region" key="slider" />

<style id="SliderTrackStyle">
    <opaque value="FALSE"/>
</style>
<bind style="SliderTrackStyle" type="region" key="sliderTrack" />

<style id="sliderThumbStyle">

    <state>
       <imagePainter method="sliderThumbBackground" path="Images/SliderThumb.png"
         sourceInsets="0 0 0 0"/>
    </state>

   <state value="PRESSED">
       <imagePainter method="sliderThumbBackground" path="Images/SliderThumbPressed.png"
         sourceInsets="0 0 0 0"/>
   </state>

</style>

<bind style="sliderThumbStyle" type="region" key="sliderThumb" />
</code>
Answer: Use Vector graphics. On one of my apps, I originally used png files, the same as you. When I switched to Vector graphics, the edges didn't tear when used on smaller buttons.


AndEngine: ClassNotFoundException

Question: I keep getting a ClassNotFoundException on AndEngine since i moved a few classfiles. I also reverted those changes after I wasn't able to fix it. Unfortunetly I can't get it back to normal..
Errorlog:
12-22 13:55:57.201: D/AndroidRuntime(5527): Shutting down VM
12-22 13:55:57.201: W/dalvikvm(5527): threadid=1: thread exiting with uncaught exception (group=0x411c7300)
12-22 13:55:57.201: E/AndroidRuntime(5527): FATAL EXCEPTION: main
12-22 13:55:57.201: E/AndroidRuntime(5527): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{de.uni_kassel.repopandroidclient/de.uni_kassel.repopandroidclient.LauncherController}: java.lang.ClassNotFoundException: de.uni_kassel.repopandroidclient.LauncherController
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.os.Looper.loop(Looper.java:137)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.ActivityThread.main(ActivityThread.java:4745)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at java.lang.reflect.Method.invokeNative(Native Method)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at java.lang.reflect.Method.invoke(Method.java:511)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at dalvik.system.NativeStart.main(Native Method)
12-22 13:55:57.201: E/AndroidRuntime(5527): Caused by: java.lang.ClassNotFoundException: de.uni_kassel.repopandroidclient.LauncherController
12-22 13:55:57.201: E/AndroidRuntime(5527):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
12-22 13:55:57.201: E/AndroidRuntime(5527):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
12-22 13:55:57.201: E/AndroidRuntime(5527):     ... 11 more

thats the manifest file im using right now:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.uni_kassel.repopandroidclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="de.uni_kassel.repopandroidclient.LauncherController"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Comment: Did you set the `AndEngine.jar` in your `Java Build Path`?
Answer: Go to project project properties click on android, add AndEngine project which you downloaded from gitHub as library. Uncheck the option "is Library"

AndEngine: ClassNotFoundException


I don't feel anxious on stage, but I perform badly

Question: I never thought myself to have stage fright. I never feel anxious or scared about performing. However, when I get on stage my performance is suddenly horrible. Easy songs become impossible. How do I stop this?
Comment: Some more detail may help to get the answer you are looking for. Do you perform with others or by yourself? What do you mean with: "my performance is suddenly horrible"? Horrible how? Do you forget the music, forget how to play your instrument, lose all sense of rhythm, lose the ability to control dynamics...?
Answer: Practice with distractions.  Practice while observing yourself in a mirror.  Practice while keeping a camera rolling.  Practice while trying to learn a poem.  If your instrument does not require your breath and voice, recite a poem while playing.
The problem is that with your usual practice, your concentration is on your play and the setup is 100% under your control and what you are accustomed to.
Play before an audience, and 30% of your focus are concerned dealing with audience and stage.  If the remaining 70% are fine for working your instrument and you can consequently cater to the audience and adapt to it, you'll be better than a recording to them.  Which is more or less the point of an actual performance.
Do not expect things to work that are at the limit of your sovereignty when practising on them on your own.  You don't want to merely prove to your audience that stuff is at the level you manage.  You want to hand them something, and if what you carry is too heavy, you'll just fall over when stretching out your hands.
Answer: Not everyone gets nervous.  Personally, I can't imagine not being nervous because music is very challenging to master.  I might say impossible.  That being said, I have advanced my performance ability considerably by learning to have laser focus on what I'm doing.  This is equal parts control and letting go.  With nothing in your mind but listening and letting the music flow through you.  As soon as you think about what your fingers are doing, you're not focusing.  If you must think about what your fingers are doing, you must practice more until it is second nature.  Seeing a masterful performance is special because it's not about the person performing it, but the music they brought to life.  But performance is not just for the virtuosos of the world, it is for everyone.


How can I expose Drupal data to external applications?

Question: How can I expose data from my Drupal site via web services to external applications such as iPhone or Android?
Answer: One of the most popular solutions is the Services module. It takes a little bit of set-up and know-how but it's very flexible in what it can output and what formats you need it. It's the solution we used at Palantir.net to provide data to our DrupalCon Chicago Android and iOS apps.
Comment: What is the best format to expose my data?JSON?
Answer: One option is to use RSS which is enabled by default. You can use RSS at http://example.com/rss.xml by default, or if you're using something like the views module, you can always set up an RSS feed for a specific view, to limit the data in the RSS feed to a specific type, or other filters.
Answer: Modules can also implement hook_xmlrpc(), and hook_xmlrpc_alter().
Depending on the data you need to exchange with the external applications, and from the format they need, you could also follow this approach.
Answer: For Drupal 8, it's best to use core REST API module. Here is a Drupal 8 Android app https://github.com/onedrupal/One-Drupal-Android that uses core REST APIs.


Compare field in derived template class

Question: I have two classes in library:
class A
{
    public:
    int x;
};

template <class T>
class B : public A
{
    public:
    T y;

};

And have method:
... Method(A &a, A &b);

How compare y from a and b if a, b always have same type
B <T>

, but type of T unknown?
Comment: "How compare y from a and b if a, b always have same type B" - but `a` and `b` have type `A`, but not `B`
Comment: how do you plan to access y using a and b in the method you described?
Answer: When you have a function,
Method(A a, A b);

You have lost the B part of the objects due to object slicing.
If you want retain the B part of the objects, you have to use references or pointers.
Method(A const& a, A const& b);

or
Method(A const* a, A const* b);

In order for Method to work correctly, you have to provide a way for the objects to be treated as B. You can use that using a virtual function in A.
class A
{
    public:
    int x;
    virtual int compare(A const& rhs) const
    {
        return (this->x - rhs.x);
    }
};

and make sure to override the function in B.
template <class T>
class B : public A
{
    public:
    T y;
    virtual int compare(A const& rhs) const
    {
       // Use the base class first.
       int r = A::compare(rhs);

       // If the base class result is adequate, return.
       if ( r != 0 )
       {
          return r;
       }

       // Do a dynamic_cast of the rhs.
       B const* rhsPtr = dynamic_cast(&rhs);

       // If the dynamic_cast didn't succeed, need
       // to figure out how to handle the case.
       if ( rhsPtr == nullptr )
       {
          // Add error handling code
       }

       return (this->y - rhsPtr->y);
    }
};

Then, in Method,
Method(A const& a, A const& b)
{
   int r = a.compare(b);
}

Comment: But if I can't change classes A and B?
Comment: @ZregerZ, if you can't change classes `A` and `B`, you have to include all the `dynamic_cast`-ing code in `Method`. That will be  almost impossible since `B` is a class template. You can't just `dynamic_cast` to `B`, you have to `dynamic_cast` to `B`. How would `Method` know what `T` to use?
Comment: @ZregerZ, exactly. That doesn't sound like it's maintainable code.
Comment: @R Sahu, Method knowns only that a and b have field y of one type.
Answer: A possible solution is to create a virtual function that will do the comparison.
Inside the body of the implementation in the derived class the type T is known and you'll have no problems.
struct Base {
  ...
  virtual bool same_y(const Base& other) const = 0;
};

template<typename T>
struct Derived : Base {
    T y;
    virtual bool same_y(const Base& other) const {
        return dynamic_cast< const Derived<T>& >(other).y == y;
    }
};

Comment: What to do if I can't change classes?
Answer: You could define Method as a template method.
template<typename T>
bool Method(const A& a, const A& b)
{
    const B<T>& first = dynamic_cast<const B<T>&>(a);
    const B<T>& second = dynamic_cast<const B<T>&> (b);
    return first.y == second.y;
}

With this approach you don't have to know the type of T inside Method. But you have to specify T when you call it:
bool areEqual = Method<int>(a, b);

Maybe that is no problem in your case.
Be aware that whenever you assign a B<T> to a variable of type A you are loosing the information that is specific to B<T> (in this case the value of y is lost). That's why I changed the signature of Method in order to take references instead of values.
Comment: Here, you have slicing problem. And I would use `dynamic_cast` anyway.
Comment: And you may also avoid copies if `first` and `second` were const reference.

Compare field in derived template class


Probability that number is divisible by 5

Question: Two numbers $x$ and $y$ are chosen at random without replacement from the set $${1,2,\cdots,5n}$$.then the probability that $x^4-y^4$ is divisible by $5$ is----
I could write down $x^4-y^4$ as $(x-y)(x+y)(x^2+y^2)$ and then i could easily figure out the possoble cases for first and second brackets but i couldnot figure out for the third bracket.
Please help me in this regard.
Thanks.
Comment: The divisibilty condition can be written $5|x=5|y$.
Answer: Note that if $x$ is not a multiple of $5$ then $x^4-1$ is divisible by $5$ (why?).
This implies that if $x$ and $y$ are not a multiple of $5$ then $x^4-y^4=(x^4-1)-(y^4-1)$ is divisible by $5$.
Can you take it from here?
P.S. Finally you will find that $x^4-y^4$ is NOT divisible by 5 iff the set $\{x,y\}$ ($5n(5n-1)/2$ choices) contains a multiple of $5$ ($n$ choices) and a not-multiple of $5$ ($4n$ choices). Hence the probability is
$$1-\frac{(n)\cdot (4n)}{\frac{5n(5n-1)}{2}}.$$
Answer: The remainders modulo $5$ of $n^4$ are periodically
$$0,1,16,81,256\to0,1,1,1,1$$
Hence $x^4-y^4$ is a multiple of $5$ when both or none are multiple of $5$.

The first drawing yields a multiple with probability $n/(5n)$. The second drawing yields a multiple with probabilities $(n-1)/(5n-1)$ or $n/(5n-1)$.
Hence the requested probability $p_1p_{2|1}+(1-p_1)(1-p_{2|1})$,
$$\frac15\frac{n-1}{5n-1}+\frac45\left(1-\frac n{5n-1}\right).$$


Dúvida com sockets(WinSocks)

Question: Boas,
Ando a aprender como trabalhar com sockets(nunca trabalhei) e decidi começar por winsocks. De momento estou a utilizar winsock2.h e no tutorial que estou a seguir cheguei a uma parte que não consigo compreender como funciona.
AQUI ESTÁ O TUTORIAL
A parte que tenho duvida é como é feito o handle dos diversos clientes.
 //add master socket to fd set
    FD_SET(master, &readfds);
       //add child sockets to fd set
    for (  i = 0 ; i < max_clients ; i++)
    {
        s = client_socket[i];
        if(s > 0)
        {
            FD_SET( s , &readfds);
        }
    }

    if (FD_ISSET(master , &readfds))
 {....}

Porque razão este if statement não é sempre verdadeiro e como funciona? O socket master está sempre definido. No inicio pensei que era porque se fazia setaos sockets dos clientes, mas nenhum deles é superior a 0.
Comment: Recomendo usar uma biblioteca crossplataform, como o boost.
Answer: No tutorial, antes do if em questão existe uma chamada para a função select. A função select vai alterar os bits de readfds de acordo com a presença ou não de atividade no respectivo socket. É por este motivo que, mesmo com o código setando o bit correspondente ao socket "master", após a chamada para select este bit pode ser resetado, e o if pode não ser verdadeiro.

Dúvida com sockets(WinSocks)


Can I draw the ROC curve from ROC_AUC Score?

Question: The question may look rediculous. The problem in my hand is a multi-class (5 class labels) classification problem and I coded it a year back. I am having the resulsts such as G-mean, F-score, and ROC_AUC score with me, but I lost my code due to the crash of my machine. I can resconstruct the code and get all the necessary details, but I am running short of time to submit the final report. I am in a need of including the ROC curves for different models in my final report. Can I plot the curves having the ROC_AUC scores calculated using the function roc_auc_score() ?
Comment: I'm not familiar with the G-mean, but I assume it is a single number?
Comment: yes it is a single number
Comment: Then my answer holds.
Answer: You probably can't.
The ROC AUC score, F-score and G-mean are all summarized measure. This means that information about the specific underlying distributions has been lost: you cannot recover raw data from summarized data.
There are an infinity of ROC curves that have a given AUC. If you know the number of data points, you might be able to restrict the number of possible curves, but you will still have multiple (many) curves to choose from, and no way to know which one was the correct one.
The only exception is if your AUC is exactly 1.0 or 0.0 and you had a perfect classification.
Comment: Thanks a lot for your answer. My AUC scores are between 0.0 and 1.0.


AngularJS - Quando devo utilizar ng-show e quando devo utilizar ng-hide?

Question: Estou vendo um tutorial, e em um certo momento ele apresenta o código dizendo que o mais correto é utilizar o ng-hide na tag DIV e mais abaixo na tag BUTTON o mesmo utilizou ng-show. Quando devo utilizar cada um deles?

 {{store.product.name}}

 ${{store.product.price}}

 {{store.product.description}}

    <button ng-show="store.product.canPurchase">Add to Cart </button>

Comment: `ng-show="!store.product.soldOut"` equivale a `ng-hide="store.product.soldOut"` .
Answer: De modo bem simples:

ng-show: quando você quiser exibir um conteúdo com alguma condição;
ng-hide: quando você quiser esconder um conteúdo com alguma condição;

Caso 01: Exibir uma div quando o valor de nome for Pedro

Caso 02: Esconder uma div quando valor de idade for menor que 18:
<div ng-hide="idade < 18">

No Caso 01, a div só será exibida se o valor de nome for "Pedro", se for qualquer outro valor, seja ele válido ou não, ela nunca será exibida. O mesmo acontece para o Caso 02, porém com a lógica inversa. A div sempre será exibida, no entanto, se a idade for menor que 18, ela não será exibida.
Observação importante
O que você deve estar ciente ao usar ng-show e/ou ng-hide é que a div (ou qualquer outro elemento usando as propriedades) ainda irá existir em seu html. O efeito deles é de apenas controlar a exibição através da propriedade css display mudando display:hidden quando precisar excluir.
Em contra partida, existe o ng-if, ele funciona de modo semelhante, veja:

Neste caso a div só será exibida se o valor de nome for Pedro.
Mas então, qual a diferença?
O ng-if não vai renderizar a div em seu html enquanto o valor não for "Pedro", ou seja, ela não existe em seu html.
Comment: +1 - Vale lembrar que usando `ng-if` objetos no DOM são destruídos/reconstruídos, enquanto que `ng-show` e `ng-hide` apenas controlam visibilidade. Importante se custos de reconstrução ou garantia de estado para `controllers` for um ponto crítico.
Comment: Bem lembrado @lbotinelly


Pair swap elements in list using Ocaml

Question: I am a Ocaml beginner, and am not able to understand tail recursiveness or list iteration. How can we iterate through list is 2s and swap the pairs?
let rec swap = function
| a :: (b :: _ as t) -> b::a::swap t | smaller -> smaller;;
let newlist = swap [1;2;3;4];;
List.iter print_int newlist;

For example, 1234, the swap function is swapping 1 and 2, and then the list head is still at 2, and its swapping 2 and 3 whereas it should be at 3 and swapping 3 and 4.
Comment: @dj007 you should edit your question with the content of your comment and explain a little bit what is not working with the code you're showing. Hint: the warning about non-exhaustiveness you're probably getting from the compiler/interpreter is important. As already said by Jeffrey Scofield, what happens when the argument of swap is of form `[a]` (a list with a single element) or `[]` (the empty list)?
Comment: You should show some code you've written and explain why it doesn't seem to be working. As a general hint, if you break a list of length n into two pieces of length 2 and n - 2, you have an easy problem to solve (of length 2) and a smaller instance of the same problem.
Comment: let rec swap = function
    | a :: (b :: _ as t) -> b ::a:: swap t;;
Answer: What you are trying to do in swap should be
let rec swap = function
    | a :: b :: tail -> b :: a :: (swap tail)
    | whatever -> whatever

This way you swap two elements on the head and proceed with what after those.
However, there is a problem here. Let's see what happens, say, in the case of swap [1; 2; 3; 4; 5; 6] call:

swap is called with [1; 2; 3; 4; 5; 6]
a matched with 1, b matched with 2, and...

....2.1. swap is called with [3; 4; 5; 6]
....2.2. inside this second call a is matched with 3, b is matched with 4, and...
........2.2.1. swap is called with [5; 6]
........2.2.2. inside this third call a is matched with 5, b is matched with 6, and ...
............188.8.131.52. swap is called with [] (empty list)
............184.108.40.206. This call returns back empty list
........2.2.3. ...and it is picked up in the previous swap call to add b and a to the start of it, producing 6 :: 5 :: [] or [6; 5]
........2.2.4. which is returned
....2.3. ...and it is picked up in the previous swap call to add (its own) b and a to the start of it, producing 4 :: 3 :: [6; 5] or [4; 3; 6; 5]
....2.4. which is returned

...and it is picked up in the previous swap call to add (its own) b and a to the start of it, producing 2 :: 1 :: [4; 3; 6; 5] or [2; 1; 4; 3; 6; 5]
which is returned as a final result

Notice how the whole chain of swap calls had to be travelled in both directions:
call 1, swap [1; 2; 3; 4; 5; 6] => call 2, swap [3; 4; 5; 6] => call 3, swap [5; 6] => call 4, swap [], returns [], now going back => call 3, returns [6; 5] => call 2, returns [4; 3; 6; 5] => call 1, returns [2; 1; 4; 3; 6; 5].
This means that the whole time the program is going "down", it should keep the previous path in the memory, so it could return back. If your list is, say, two million entries, the whole path will be one million calls, and it should be kept in memory. You'll run out of stack space if you run such thing.
How to solve this problem? The usual technique is to use some kind of "accumulator".
let rec swap_helper acc = function
    | a :: b :: tail -> swap_helper (a :: b :: acc) tail
    | a :: [] -> a :: acc
    | [] -> acc ;;

let swap2 lst = List.rev (swap_helper [] lst)

What are those functions? Let's try to see what happens if we call swap2 [1; 2; 3; 4; 5; 6]. It starts with calling swap_helper [] [1; 2; 3; 4; 5; 6].

a is matched with 1, b is matched with 2, tail is matched with [3; 4; 5; 6], so we call swap_helper [1; 2] [3; 4; 5; 6]. But lo and behold! When this next call returns, we are not doing with the result anything at all, so there is no reason to go back -- compiler will produce the code to  return the result we'll get in swap_helper [1; 2] [3; 4; 5; 6] immediately, without going back to original code -- because there's nothing left to do with that result in the original call. This is called tail call optimization.
Now we are in swap_helper [1; 2] [3; 4; 5; 6] call, where a is matched with 3, b is matched with 4 and tail is matched with [5; 6], so we call next swap_helper [3; 4; 1; 2] [5; 6] and there's again nothing left to do after that, so we are not going to return here anymore!
So, swap_helper [3; 4; 1; 2] [5; 6] call. Here a is 5, b is 6, tail is []. We proceed to swap_helper [5; 6; 3; 4; 1; 2] [] and we are not going back here anymore, since there's nothing left to do!
swap_helper [5; 6; 3; 4; 1; 2] [] hits the last case of match and returns immediately [5; 6; 3; 4; 1; 2] -- but not to any intermediate swap_helper calls, they are already forgotten, there's no work to do in those left -- but straight to the original swap2 call!

Now in swap2 we reverse the list we got from swap_helper and get our [2; 1; 4; 3; 6; 5], as desired.
So, to repeat: in this code when swap_helper calls itself, there is nothing left to do, so there's no reason to return, so there's no reason to spend memory to remember "way back", as we are not going to go back. In the original code we could not do that, because swap was calling itself and still  had to glue a and b to the result of that second call after it's ready.
Comment: I understand. Thank you so much for the answer ! Sorry if it sounded silly, this is my first time with functional programming.
Answer: The existing answer doesn't explicitly point out the key misunderstanding causing this problem. The issue lies in the associativity of as.  In the pattern a :: (b :: _ as t) the as binds t to the entire b :: _ pattern. as will bind the entire pattern to its left. Parentheses can be used to disambiguate.
Therefore, when swap t is called, t is the entire tail, and not the tail of the tail as was clearly intended. If we make that one change, the function works correctly.
# let rec swap = function
    | a :: (b :: t) -> b::a::swap t
    | smaller -> smaller;;
val swap : 'a list -> 'a list = <fun>
# swap [1;2;3;4];;
- : int list = [2; 1; 4; 3]

We might clean this up a bit for readability.
let rec swap = function
  | a::b::t -> b :: a :: swap t
  | lst -> lst

Pair swap elements in list using Ocaml


CCK doesn't find the Image module on Drupal 7

Question: After successfully migrating from Drupal 6 to Drupal 7, I wanted to migrate my CCK fields to core fields. I downloaded CCK for Drupal 7, and its field migrate module.
However, for all of my image fields, I got this error:

Missing field module: 'image'. This field cannot be migrated.

What is that module 'image' that is missing? There is no more imagefield for Drupal 7, as it is supposed to be part of core.
Comment: Does the image module actually exist? Have you tried manually enabling it? The files should be in [web-root]/modules/image/
Answer: Actually, the Image module is part of Drupal core. Enable it, and the error should vanish.

If you don't find the module listed between the modules, then you need to copy the Drupal files again on your server.
If the Image file is already present in your web server, it is enabled, and CCK keeps saying it cannot find the module, then open an issue report for CCK.
Comment: You are right! I love you!
By the way, this should be clarified in the translations. If it said "disabled" and not "missing", I would have found straight away.
Comment: The message could say the module is disabled, or missing. At least, users would check first if they need to enable it, and they will notice if the module is not present. Considering the module is part of Drupal, maybe the message error should also give more information. The function used in these cases is [module_exists()](http://api.drupal.org/api/drupal/includes%21module.inc/function/module_exists/7) which (despite the name) checks the module is enabled; if the module is not enabled, the function returns `FALSE`.
Comment: A little necro I know, but this doesn't work for me. The D7 Core 'Image' module is enabled but the Content Migrate page (/admin/structure/content_migrate) is still reporting that `Missing widget: The 'image' widget is not available for the field_background_image field, it will be set to the default widget.` I've cleared cache and all, still coming up as an issue - anyone got any thoughts?


How to pack a web application

Question: I'm buiding a web application (php or python). After finishing the project, i will have to transfer it to  the customer. For security reason, i want another one can't view source and database.
My Platform is Linux
Can you guess me solution ?
Comment: What you are looking for is not called "packing" but "obfuscation" and maybe some sort of compilation. By looking for those words you will find several solutions. Still, questions of "suggest me a solution" are not welcome on StackOverflow.
Comment: @EugeneMayevski'EldoSCorp sorry, my english is not so good so i express hardly :(
Answer: The Best tool to encode your PHP code is to use
http://www.zend.com/en/products/guard/
Or
http://www.ioncube.com/
and if you are looking for some thing basic, this is free
http://www.phpencode.org/

How to pack a web application


Why is r negative | Polar Coordinates

Question: So, I understand that the general coordinates in the Polar Coordinate system takes the form $(r,\theta) $. From what I've read, $\theta$ is the angle made with positive x-axis and $r$ is the distance from the origin. Clearly, distance cannot be negative, so why can r be negative when dealing with polar coordinates?
Comment: You could see [this post](http://math.stackexchange.com/questions/1390581/how-can-r-be-negative-when-dealing-with-polar-coordinates?rq=1) which is very similar
Answer: If r is negative you start on the other side (the negative x-axis). So $(-3, \frac{\pi}{3})$ is actually the same point as $(3, \frac{4\pi}{3}).$

Why is r negative | Polar Coordinates


ASP.NET Repeater Control linking to detailed view via QueryString parameters

Question: I have a Repeater Control using an XMLDataSource to produce a list of movies (Movies.aspx). I need to link to a detailed page via query parameters like MovieDetails.aspx?movie=Matrix. What control do I use on the MovieDetails.aspx page to render a single movie, preferably using ItemTemplate and my own HTML.
My data source:
<asp:XmlDataSource ID="MoviesXmlDataSource" runat="server"
    DataFile="~/Movies.xml" XPath="movies/movie"></asp:XmlDataSource>

I read the StackOverflow post Send string with QueryString in Repeater Control in ASP.net and list my items via a repeater like this:
    <asp:Repeater ID="Repeater1" runat="server" DataSourceID="MoviesXmlDataSource">
    <HeaderTemplate>

    </HeaderTemplate>

    <ItemTemplate>

            <a href="MovieDetails.aspx?movie=<%#Eval("title")%>">
            <img src="Images/<%#Eval("image") %>" />

            <%#Eval("title") %>

    </ItemTemplate>

    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

On my MovieDetail.aspx I get the query string parameter as expected. However, I don't know how to fetch this item from my XMLDataSource and render it nicely. I figured out how to do this using GridView and then render a DetailsView depending on what you click in the grid, but it's so ugly. Repeater lets me specify my own HTML, but only for a list and not a single item.
Answer: The whole idea of the Repeater control is to display a set of data in a consistent manner. And the HTML you apply is actually for a single item in a list of items. And if i were you, i would be using a  table to display the items. Title in one column, Image in another, details in another etc. Or you could use a
Title
--------
Image  |   Description Line 1
       |   Description Line 2
       |   Description Line 3
       |   Description Line 4
--------

Title
--------
Image  |   Description Line 1
       |   Description Line 2
       |   Description Line 3
       |   Description Line 4
--------

approach.
The only thing that is stopping you from getting a nice list of movies is the knowledge of HTML (which you already know) and creativity! Let your imagination run wild ;)

Lists
would
definitely
suck
in
this
scenario
:(
Comment: I understood the purpose of the repeater, and I have a nice list of movies already. My problem is how to render a single movie on a different page.

How can I fetch a single item from an existing data source, and then render it with pure HTML?
Answer: I just figured this out myself. I didn't realize that I could simply access my XMLDataSource from my code behind. I don't have to bind it to any control. Here is my solution:

Upon PageLoad, get the url parameter movie
Convert MoviesXMLDataSource to an XmlDocument
Fetch the single node where title matches my movie parameter
Fetch title, description and image link and store as variables
In the aspx, render normal HTML and insert <%=title %> and so on...
protected void Page_Load(object sender, EventArgs e)
{
   this.movieTitle = Request["movie"];

   string xpath = String.Format("/movies/movie[@title=\"{0}\"]", movieTitle);
   XmlDocument doc = MoviesXmlDataSource.GetXmlDocument();
   XmlNode node = doc.SelectSingleNode(xpath);

   this.title = node.Attributes["title"].Value;
   this.description = node.Attributes["description"].Value;
   this.image = node.Attributes["image"].Value;
}

And in the aspx I render stuff as normal:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<asp:XmlDataSource ID="MoviesXmlDataSource" runat="server"
    DataFile="~/Movies.xml" XPath="movies/movie">
</asp:XmlDataSource>

<%=title %>

    <img src="<%=image %>"/>

    <%=description %>

</asp:Content>

In the end this was really simple. I just got confused by forcing myself to use a control.


How would I write multiple "if" conditions in one line in timber/twig?

Question: I have a situation where I would like to write multiple "if" condition in one line such as example: {% if room_status == 'For Rent' and not 'Booked' %} this is obviously not working but you get the picture of what I am trying to accomplish.
But have no idea how to write this other that doing this:
{% if room_status == 'For Rent'%}
  {% if room_status != 'Booked' %}
    {# <Then run some code here> #}
  {% endif %}
{% endif %}

Any suggestions greatly appreciated!
Answer: From the Twig If Documentation:

For multiple conditions, and and or can be used:

{% if temperature > 18 and temperature < 27 %}

It's a nice day for a walk in the park.

{% endif %}

So, in your case this should work:
{% if room_status == 'For Rent' and room_status != 'Booked' %}
    {# <Then run some code here> #}
{% endif %}

Although it seems to me that you don't really need the second check. The room_status variable can only contain one value, right? It can't be both 'For Rent' and 'Booked' at the same time, it's either one or the other.


Debian/Ubuntu: How to select predefined collections after installation

Question: How do I select predefined collections (those you can select during installation of Ubuntu) after the installation? I read somewhere this is possible, can't for my life find where though.

(source: ubuntugeek.com)
Answer: tasksel --list-tasks

will lists all the possible tasks you can install.
tasksel install <task>

will install it.
man tasksel

is your friend.
Comment: Thanks a billion! Just what I was looking for. Running just "tasksel" brings up the GUI in the picture, btw
Comment: Googled and found my own Q. Seems you have to install `tasksel` yourself in 11.04.


Electric guitar's 6th string buzzing, but through the amplifier, the buzz sound is not coming. Anything to be concerned about?

Question: I just bought a new Cort Les Paul electric guitar.
Except for the 6th string, all other strings are working fine. No buzzing.
But the 6th string (fattest one), on plucking, is buzzing when not connected to the amplifier. However, the buzz sound is not coming through the amplifier when it is connected.
So considering the above scenario, is there anything wrong with the guitar's 6th string? Or is this buzzing sound a normal thing to happen?
Your help will be highly appreciated.
Thanks.
Comment: Is the buzzing when the open string is played, or on particular frets, or what? You could raise the bridge/saddle for that string, or on that side, a little, but if it's not coming through the amp., don't worry, unless it gets louder. Maybe  a reason to take it back for checking - it's what should happen with potentially faulty goods.
Comment: @Tim I just checked by connecting my headphone. The buzz sound is also noticeable in the headphone audio. On 5th string (very little) and 6th string (significant). On playing open note or open string, there is no buzz sound.
Answer: On that guitar, there should be an adjustable saddle, where the string goes over the bridge. You should have a small Allen (hex) key, which fits into small holes on either side of that saddle. Screwing clockwise will raise the string's height, and you'll reach a point where the buzzing stops.


Replace all occurences of string in column MYSQL database

Question: I am working with a database with a column which consists of data of what I think is a GUID, c92e5daa-ae5b-4d8e-a20d-9c1f660a7081. I have 4 of these which occurs several times and I want to replace then with something more convenient like this:
c92e5daa-ae5b-4d8e-a20d-9c1f660a7081 --> String1
c92e5daa-ae5b-4d8e-a20d-9c1f660a7081 --> String2
c92e5daa-ae5b-4d8e-a20d-9c1f660a7081 --> String3
c92e5daa-ae5b-4d8e-a20d-9c1f660a7081 --> String4

Now I know that I have a few options. I could run a SQL query with the replace function, but that won't do it since the db is always getting new data.
I've been thinking about replacing them with conditional statements in my program, but I'm not sure about that one either.
Any ideas of what would be the cleanest and best way of solving this?
Answer: IF you have currently-existing data in your database, I suspect the simplest solution is to run the update using a replace function, to modify your currently existing data, and then:
Perform your string validation and manipulation (in this case, checking its value and modifying it accordingly), in your application layer, to prevent ever inserting these strings in the database in the future. This has the advantage of simplicity.
You could, for instance, construct a dictionary type object and store the strings you want to replace as keys, with the replacement values as values.  Then, when inserting, just check the dictionary for whether a key exists, if so, substitute its value.
Comment: Your first suggestion is probably the best, but unfortunately I don't have control of the insert queries at the application layer. What my application does is exporting a sqlite database as a csv file to import it in a Mysql database so that I can use the data remotely. I'm thinking about making a powershell script that runs the query "UPDATE table SET column="String1" WHERE column="c92e5daa-ae5b-4d8e-a20d-9c1f660a7081" everytime I insert new data. (as anwered by user1403333). I just need to run the script once a day.
Comment: That will certainly work, but I think if your tables grow very large at all, this approach will quickly become terribly inefficient (in terms of overhead)
Comment: Redbeard011010 , your right. I much rater do it to the data I'm inserting which is 4-6 rows once a day. Could I do the UPDATE query with a WHERE clause and replace the GUIDs for a specific date? Because then I could replace all my rows once and from then on only replace the newly added rows onnce a day?
Answer: UPDATE table SET column="String1" WHERE column="c92e5daa-ae5b-4d8e-a20d-9c1f660a7081"

Comment: If the new strings are a competently new type of data, create a new column for them and make the application(s) that write to the table start writing to both columns. Once that's in place, make all readers use the new column and then dispose of the old column (modifying the writers to stop using it as well).
Comment: This is not a complete answer.  Show him how to store "string1" etc in to another table and then how to join the tables.


MVC bootstrap dropdownlistfor writable

Question: I am doing an MVC5 Bootstrap Application. I have a common dropdownlistfor
like this
 @Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries, new { @class = " Required ", @onclick = "hide();", @id = "Country_id" })

I have a Controller Method called AvailableCountries that brings all countries.
What I need is the ability to write a country in case it is not in the list.
I know there is a  bootstrap-select.js but I do not find an example how to use it and I do not if there is another way to do it.
Thanks
Comment: Not related, but including `new { @id = "Country_id" }` is a bit pointless - it already has that `id` attribute
Answer: the easiest way to do this would probably be to add an "Other" option to the bottom of your Country list. Then they select "Other" have another freeform textbox appear using JQuery so they can write their country in.
Then in your post controller you just need to have some logic that takes the value from the extra textbox when "Other" was selected

MVC bootstrap dropdownlistfor writable


How to know the information of USB endpoints?

Question: How can I determine the number and type of endpoints(control - IN/OUT,interrupt-IN/OUT?) my USB device is having.DOes it differs if I plug the same device onto different hosts(Linux,Windows,Mac)
Answer: You could use libusb.  It runs on all of those platforms and it has functions for retrieving the configuration descriptor from the device.  You could then parse the configuration descriptor to figure out how many endpoints there are.
Or you could just run lsusb -v, which will show you tons of information about your device.


Visual Studio won't find references

Question: I'm working with some application handed over by another person in which I must document the requirements, build and deploy processes.
The problem here is that Visual Studio (2005) is throwing a lot of errors since it can't find the references for the dlls.
This obviously won't let VS build the project.
Everything works fine on the persons computer but not on mine, even though the project references the same folder where the dlls are, the bin folder.
How can I circumvent these problems and get VS to properly reference the dlls?
The following printscreen shows the references screen for the project.
Comment: Check the source of the project file (.vbproj), you can find the references there. I guess they are hard coded to a specific path on the other person's PC. Personally, I always create a separate folder with all the referenced DLL's in it (if they are not in the GAC) and reference them from there (using a relative path).
Comment: Clearly you'll need to read that document you are supposed to write first :)  We can't help you find these files either of course.  I suspect it going to be difficult when you have had programmers working on this project that thought that "DLL" was a good name for a project.
Answer: My guess is that your DLL uses a more recent .NET framework than your application does.
Check the properties for your DLL source (right-click on the DLL code in the solution explorer and choose Properties). Go to Application - Target .NET framework and compare the version to the one the application itself uses (right-click on the project code). Note: under your application properties check both the settings under Application - Target .NET framework AND under Publish - Prerequisites.
Comment: I'm surprised that this answer doesn't have more upvotes!
Comment: this is the best answer, you cannot add a reference for a newer version of .NET framework
Answer: For what it's worth, even after changing the .vbproj file and removing many lines about hard coded values,
I eventually checked out the project again removed all references to the given DLL and then added it using the GUI.
Lesson learned, don't try to change out one DLL for a newer version without using VB2005 GUI.
The easiest solution will probably be to transfer everything to another project. It will be incredibly time consuming to find where visual studio has left the hard coded path at.
WOOT!!!! Compile the DLL file to a lower version of the .NET framework, and it will fix the problem!!!!
Answer: The paths in the project file cannot be the same or the assemblies referenced have a different version.
It might be worth unloading your project and the editing it to inspect where it's looking and for what version.
Answer: I had the same problem with an older Visual Studio Project that I opened in Visual Studio 2008. I tried to add new references to the project and got permanent errors that the dll's cannot be found. After the migration of the Project to Visual Studio 2010 I got the following error message when I tried to add a new reference:
'mySample.dll' or one of its dependencies, requires a later version of the .NET Framework than the one specified in the project. You can change ...
After changing the projects .NET Framework to a newer version everything works fine.
Answer: Good suggestions in other answers. In my case, it was because the libraries weren't copied (downloaded) successfully: the files existed, but were 0 kB.
Answer: Did a clean, which removed all the DLL's and then VS2008 complained it couldn't find the references (Duh!!!) and wouldn't rebuild....luckily I had and old version of the dll's and replaced them in the directory AND THEN did a rebuild to replace them...all references are now OK and we're back to normal....good old VS 2008

Visual Studio won't find references


Show views display based on exposed filter value

Question: I've a views with 2 different displays which are Picture View and List View, both sharing the same exposed filter(the query string).
I have an exposed filter block, one of the exposed filter(Radio Button) is View by: 1) Picture view 2) List View
How to show the respective views result based on user selection (View By filter)?
Updates:
My intention is to let the user to choose which Display she wants to see before clicking the Apply/Search button of the exposed filter block. There is only ONE display at a time, no tabbed/links for multiple display option. Solution similar to Views Mode module is not i looking for.
Answer: I find out two methods here.
Method 1: Use set_display function
function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  $view->set_display('view_photo');
 }
}

Method 2: drupal_goto (if the two displays are not sharing the same exposed filter)
function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  //build up the the query string here
 $query['filter_a'] == 'xxx';
 drupal_goto('viewphoto_path',array('query' => $query));
 }
}

To my case, i used Method 2.
I am really new to drupal, and not sure are these methods will cause any problem or not.
Let me know if they are ok.
Answer: May be Views Modes module can help you. It works different than you want, but this is an alternative method.

A Drupal Views display plugin which provides alternate display modes that can be switched to for a single View. This allows exposed filter parameters or contextual filters to be kept active while switching display mode.
Comment: Thanks for your suggestion. I've tried this module before this, not exactly what i want. The view has to be executed then only you can choose other view mode. I wish to choose the view mode before that.
Comment: @user20395 http://drupal.stackexchange.com/questions/65928/how-to-attach-a-view-display-switch-to-a-view - this discussion?
Comment: nope. this is more to the Views Mode solution.
Comment: @user20395 I have never faced with such a task. Let me know if you find a solution:)
Comment: hi please take a look of my answer.
Answer: I guess this could help you getting ride of the problem,
I have created two view displays (as blocks)

Block name: title_image (Custom Themed with views-view-field--custom-view-theming--block-1--title.tpl.php)
Block name: image  (Custom Themed with views-view-field--custom-view-theming--block-2--field-image.tpl.php)

views-view-field--custom-view-theming--block-1--title.tpl.php

    <a href="/?q=node/<?php print_r($row->nid);?>" title="<?php print_r($row->node_title);?>" style="float: left; padding-right: 20px;">
      <img width="170" class="bordered-image -align" title="<?php print_r($row->node_title);?>" src="sites/default/files/field/image/<?php print $row->field_field_image[0]['raw']['filename']; ?>" />

     <a alt="" title="<?php print_r($row->node_title);?>" href="/?q=node/<?php print_r($row->nid);?>"> <?php print_r($row->node_title);?>

      <?php if($row->field_body) print $row->field_body[0]['raw']['value']; ?>

views-view-field--custom-view-theming--block-2--field-image.tpl.php

        <img width="170" class="bordered-image -align"  src="sites/default/files/field/image/<?php print $row->field_field_image[0]['raw']['filename']; ?>" />

Both the contents are themed separately now we need to couple both the tpl files in a common place. Since both the displays are created as blocks we can add a comon wrapper in the following tpl views-view--custom-view-theming--block.tpl.php.
views-view--custom-view-theming--block.tpl.php

<input type="radio" name="tab-group" <?php if ($view->current_display == "block_1") print_r("checked")?>>

<label for="tab-<?php print_r($view->current_display);?>">Tab One<?php print_r($view->current_display);?>

<div class="<?php print $classes;?>">
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php if ($header): ?>

      <?php print $header; ?>

  <?php endif; ?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

  <?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

Add the following css :
    /** Tabbing Starts here**/

/** Drupal region class .region-content**/
    .region-content {
      position: relative;
      min-height: 200px; /* This part sucks */
      clear: both;
      margin: 35px 0 25px;
      background: white;
    }
    .tab {
      float: left;
    }
    .tab label {
      background: #eee;
      padding: 10px;
      border: 1px solid #ccc;
      margin-left: -1px;
      position: relative;
      left: 1px;
      top: -29px;
      -webkit-transition: background-color .17s linear;
    }
    .tab [type=radio] {
      display: none;
    }
/** Drupal region class .view-custom-view-theming **/
    .view-custom-view-theming {
      position: absolute;
      top: 14px;
      left: 0;
      background: white;
      right: 0;
      bottom: 0;
      padding: 20px;
      border: 1px solid #ccc;
      -webkit-transition: opacity .6s linear;
      opacity: 0;
    }
    [type=radio]:checked ~ label {
      background: white;
      border-bottom: 1px solid white;
      z-index: 2;
    }
    [type=radio]:checked ~ label ~ .view-custom-view-theming {
      z-index: 1;
      opacity: 1;
    }

Sample output :
Comment: Thanks for your answer, I believe you misunderstood my question. Please see the updates of my question. Thanks!


Why is the 11th often sharpened?

Question: A book I'm reading suggests that there are two reasons that the 9#11 chord is more common than the 11th chord, and I don't understand either.

First, the natural 11th interferes with our ability to hear the root of the chord, because it's the same note as the subdominant, which is a lower note. Also, it clashes with the major 3rd.

I (having a very untrained ear) don't notice a difference in ability to hear the root between C9 and C11. The 11th is more than an octave above the root. Why would hearing the subdominant there make it harder? Is commonly agreed that it is?
Why is it problematic that the 11th clashes with the 3rd, but not that the #11th clashes with the 5th? Is this because the third is more characterising of a chord than the fifth?

(Of course whatever sounds right is right and there are no rules, but I believe there is value in understanding what's written in theory books either way.)
Comment: Comment rather than answer. An 11th chord to me usually sounds more like a sus (Yes, the 3rd is there already!), and the #11 sounds like a 'b12', as in it's the 5th (12th) that's been changed, flattened,  rather than the 11th sharpened.
Comment: @Tim Thank you. It's very helpful for me to hear how others perceive chords, as it often differs from my perception. Maybe because I didn't grow up around music.
Answer: The clash with the 3rd is the more important factor. The 3rd and 7th are responsible for describing the quality of the chord and are therefore very important notes, but the 5th (if it's a perfect 5th) doesn't really add anything. So the 5th is often omitted from a voicing, whether because it's clashing or because we don't have enough fingers. Try it yourself: Play C E G B♭ and compare how it feels when you remove the E vs. when you remove the G.
Regarding the first reason stated: I think this effect is present, but it's very slight. It's going to be hard to experience in isolation, because when you set out to play a C11 chord you are priming yourself to interpret C as the root. If you were to encounter this chord in context, and probably without the clean stacked-thirds voicing, you might find it to be more ambiguous.

Why is the 11th often sharpened?


Mounting EKS EFS with CSI Times Out before Pod Comes Up

Question: I am using EKS with Kubernetes version 1.15 and when I create a Storageclass, Persistent-Volume, Persistent-Volume-Claim, and Deployment the pod fails with:
Warning  FailedAttachVolume  71s (x2 over 3m11s)  attachdetach-controller              AttachVolume.Attach failed for volume "efs-pv" : attachment timeout for volume fs-<volume>
Warning  FailedMount         53s (x2 over 3m8s)   kubelet, ip-<ip-address>.ec2.internal  Unable to mount volumes for pod "influxdb-deployment-555f4c8b94-mldfs_default(2525d10b-e30b-4c4c-893e-10971e0c683e)": timeout expired waiting for volumes to attach or mount for pod "default"/"influxdb-deployment-555f4c8b94-mldfs". list of unmounted volumes=[persistent-storage]. list of unattached volumes=[persistent-storage]

However when I try the same without building the Persistent-Volume it is successful, and creates its own that seemingly skips CSI. This is what I am working with:
deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: influxdb-deployment
spec:
  selector:
    matchLabels:
      app: influxdb
  replicas: 1
  template:
    metadata:
      labels:
        app: influxdb
    spec:
      containers:
      - name: influxdb
        image: influxdb:1.7.10-alpine
        ports:
        - containerPort: 8086
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/lib/influx
      volumes:
      - name: persistent-storage
        persistentVolumeClaim:
          claimName: efs-claim

storageclass.yaml:
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: efs-sc
provisioner: efs.csi.aws.com
reclaimPolicy: Retain

persistent-volume.yaml:
apiVersion: v1
kind: PersistentVolume
metadata:
  name: efs-pv
spec:
  capacity:
    storage: 5Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Retain
  storageClassName: efs-sc
  csi:
    driver: efs.csi.aws.com
    volumeHandle: fs-<volume-id>

persistent-volume-claim.yaml:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: efs-claim
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: efs-sc
  resources:
    requests:
      storage: 5Gi

Any idea on what is happening?
Answer: would you mind trying to create the CSIDriver object and the Daemonset related as well?
apiVersion: storage.k8s.io/v1beta1
kind: CSIDriver
metadata:
  name: efs.csi.aws.com
spec:
  attachRequired: false
---
# Node Service
kind: DaemonSet
apiVersion: apps/v1
metadata:
  name: efs-csi-node
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app: efs-csi-node
  template:
    metadata:
      labels:
        app: efs-csi-node
    spec:
      nodeSelector:
        kubernetes.io/os: linux
        kubernetes.io/arch: amd64
      hostNetwork: true
      priorityClassName: system-node-critical
      tolerations:
        - operator: Exists
      containers:
        - name: efs-plugin
          securityContext:
            privileged: true
          image: amazon/aws-efs-csi-driver:latest
          args:
            - --endpoint=$(CSI_ENDPOINT)
            - --logtostderr
            - --v=5
          env:
            - name: CSI_ENDPOINT
              value: unix:/csi/csi.sock
          volumeMounts:
            - name: kubelet-dir
              mountPath: /var/lib/kubelet
              mountPropagation: "Bidirectional"
            - name: plugin-dir
              mountPath: /csi
            - name: efs-state-dir
              mountPath: /var/run/efs
          ports:
            - containerPort: 9809
              name: healthz
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /healthz
              port: healthz
            initialDelaySeconds: 10
            timeoutSeconds: 3
            periodSeconds: 2
            failureThreshold: 5
        - name: csi-driver-registrar
          image: quay.io/k8scsi/csi-node-driver-registrar:v1.3.0
          args:
            - --csi-address=$(ADDRESS)
            - --kubelet-registration-path=$(DRIVER_REG_SOCK_PATH)
            - --v=5
          env:
            - name: ADDRESS
              value: /csi/csi.sock
            - name: DRIVER_REG_SOCK_PATH
              value: /var/lib/kubelet/plugins/efs.csi.aws.com/csi.sock
            - name: KUBE_NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
          volumeMounts:
            - name: plugin-dir
              mountPath: /csi
            - name: registration-dir
              mountPath: /registration
            - name: efs-utils-config
              mountPath: /etc/amazon/efs
        - name: liveness-probe
          image: quay.io/k8scsi/livenessprobe:v2.0.0
          args:
            - --csi-address=/csi/csi.sock
            - --health-port=9809
          volumeMounts:
            - mountPath: /csi
              name: plugin-dir
      volumes:
        - name: kubelet-dir
          hostPath:
            path: /var/lib/kubelet
            type: Directory
        - name: registration-dir
          hostPath:
            path: /var/lib/kubelet/plugins_registry/
            type: Directory
        - name: plugin-dir
          hostPath:
            path: /var/lib/kubelet/plugins/efs.csi.aws.com/
            type: DirectoryOrCreate
        - name: efs-state-dir
          hostPath:
            path: /var/run/efs
            type: DirectoryOrCreate
        - name: efs-utils-config
          hostPath:
            path: /etc/amazon/efs
            type: DirectoryOrCreate
---

or skip the manual process above and just execute:
kubectl apply -k "github.com/kubernetes-sigs/aws-efs-csi-driver/deploy/kubernetes/overlays/stable/ecr/?ref=release-1.0"

then try to spin up your stuff again.
hope it helps.
See here for possible release updates.


has_many or join - what's the 'rails way' to use my table?

Question: I have a database that keeps track of accidents. Each accident can have multiple causes. Each cause has a friendly name in a 3rd table. What's the 'rails way' to create this association?
Here's what I have:
create_table "accidents", force: true do |t|
  t.text     "notes"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "causes", force: true do |t|
  t.integer  "accident_id"
  t.integer  "cause_name_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "cause_names", force: true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end
CauseName.create :name => "DUI"
CauseName.create :name => "Speeding"

Accident:
class Accident ActiveRecord::Base
  has_many :causes
end

Causes:
class Cause < ActiveRecord::Base
  belongs_to :accidents
  has_one :cause_name
end

cause names:
class CauseName < ActiveRecord::Base
  belongs_to :causes
end

It seems like to be properly "ORM"'d, I'd use it like this:
Accident.causes.first.cause_name.name #speeding
a = CauseName.find(1)
Accident.causes.first.cause_name = a #set and saved successfully

I've been trying a variety of things, but I can't seem to get my associations to work the way I'd expect. I know I'm not using it right.
I'm very new to rails and activerecord, and horrible with databases... the schema I'm working with was designed by our dba who will be doing reporting on the table, but knows nothing about Ruby or ActiveRecord.
What's the best approach in my situation? Am I even using this thing right?
Answer: In your case, I'd suggest not splitting causes into two tables. Just cram name into causes table and call it a day.
Then you can easily query like @accident.causes.first.name
Comment: Part of the reason we broke it out in the first place is to maintain the ability to tweak the cause_names slightly over time. For instance, we might go from "Speeding" to "Speeding - Motorcycle" and add "speeding - car". Obviously, in a real world example we'd add another column entirely for automobile_type, but you get the general idea. Is it poor design to just save the plain language string "speeding"/"DUI" in the table? seems like it wouldn't be  scalable? What's your opinion?
Comment: You're right. If you want to manage names of the causes, there's nothing wrong with what you're doing. Don't forget to add indexes to foreign keys and `name`.
Answer: I think you have your belongs_to and has_one methods placed incorrectly in your Cause - CauseName association.
Quoting the official guide:

If you want to set up a one-to-one relationship between two models,
  you'll need to add belongs_to to one, and has_one to the other. How do
  you know which is which?
The distinction is in where you place the foreign key (it goes on the
  table for the class declaring the belongs_to association), but you
  should give some thought to the actual meaning of the data as well.
  The has_one relationship says that one of something is yours - that
  is, that something points back to you.

So, in your case, it should be like this:
class CauseName < ActiveRecord::Base
  has_one :cause # Note that I have changed :causes to singular too
end

class Cause < ActiveRecord::Base
  belongs_to :accident # <- Singularized too
  belongs_to :cause_name
end

Comment: That's exactly where I went wrong. Also, it's important to remember to use the singular reference when using has_one and belongs_to, something I had mistaken. I'm surprised that ActiveRecord didn't bark at me when I made this mistake. I'm unsure if it's because it fixed it for me, or because it failed silently. Odd.


Can I replace TRUNCATE + COPY + ANALYZE with TRUNCATE + COPY/FREEZE in PostgreSQL 9.3

Question: I am trying to optimize my bulk loading routine.
Currently I load data in steps (I am not following SQL syntax below, just the algorithm):
BEGIN
TRUNCATE table
COPY into table
ANALYZE table
COMMIT

Before PostgreSQL 9.3 this was the only recommended way to re-load a table. Version 9.3 introduces FREEZE option that can be used with COPY command. Standard documentation says:

FREEZE
Requests copying the data with rows already frozen, just as
  they would be after running the VACUUM FREEZE command. This is
  intended as a performance option for initial data loading. Rows will
  be frozen only if the table being loaded has been created or truncated
  in the current subtransaction, there are no cursors open and there are
  no older snapshots held by this transaction.

My immediate question is whether I still need to run ANALYZE after COPY/FREEZE. The standard doc doesn't give any direct recommendation on it. Would the following sequence suffice or do I still need to run ANALYZE?
BEGIN
TRUNCATE table
COPY/FREEZE table
COMMIT

Thanks!
Answer: Yes, you should still ANALYZE to force immediate table statistics generation after you COPY the data in.
Whether tuples are frozen or not has nothing to do with stats, it's a way to avoid later anti-wraparound vacuum activity.
Comment: It was wishful thinking on my part. That would be a nice feature though, it could save server resources if it could collect statistics as data is being loaded. Thanks Craig.
Comment: @cherio It'd be interesting to do that, yeah ... `COPY ... WITH STATISTICS`. Patches are welcome :p


Distinct one value from multiple same records result query

Question: I have this result on stored procedure in sql server (result of multiples left join):
http://sqlfiddle.com/#!18/be597/1
I need to send on each email the content of columns article, code.
I thought about the function GROUP_CONCAT but I do not think that this is the good solution because it formats me the text in the query.
SELECT mail, GROUP_CONCAT(CONCAT('Article: ', article, ' - Code: ', code), '\n') FROM mail GROUP BY mail

I would like to keep the data in the stored procedure for later use.
How can I do it in sql ?
I imagine that this should be a recurring problem with SQL queries but I am a beginner so I allow myself to ask the question.
Answer: GROUP_CONCAT is a Mysql feature, SQL Server doesn't support this kind of function. And you could use to keep format by FOR XML PATH
SELECT
    mail,
    STUFF((
    SELECT ', ' + article
    FROM mail
    WHERE (mail = mainMail.mail)
    FOR XML PATH (''))
    ,1,2,'') AS Articles,
    STUFF((
    SELECT ', ' + CAST(code AS VARCHAR(5))
    FROM mail
    WHERE (mail = mainMail.mail)
    FOR XML PATH (''))
    ,1,2,'') AS Codes
FROM mail mainMail
GROUP BY mail

Demo

I would like to keep the data in the stored procedure for later use.

You don't keep the data in the stored procedure. You keep the query in the stored procedure and execute.
Comment: Yes, my bad, i have used GROUP_CONCAT on my tests in MySQL. This query return results like GROUP_CONCAT. Is it possible to get article and code on separate columns instead comma ? I need to keep formated data for later use.


Let $(a_n)_{n\in \mathbb N}$ be a bounded non-negative sequence, with density zero converges to 0

Question: Let $(a_n)_{n\in \mathbb N}$ be a bounded non-negative sequence. Show that
$$\lim_{n\rightarrow \infty}\dfrac{1}{n}\sum_{k=0}^{n-1} a_k = 0\tag{1}$$ if and only if $$\lim_{n\rightarrow \infty}\dfrac{1}{n}\sum_{k=0}^{n-1}a_k^2= 0. \tag{2}$$
I am aware of the following characterization of (1), and this question on MSE:
(1) if and only if there exist a subset $J\subset \mathbb N$ with density zero, such that $(a_n)\xrightarrow[n\notin J]{n\rightarrow \infty}0$.
How can I use this to prove (2)?
Im thinking for (1) implies (2), one can say that for the same subset $J\subset \mathbb N$, one has $$(a_n^2)\xrightarrow[n\notin J]{n\rightarrow \infty}0.$$
As for (2) implies (1), i can repeat the proof for constructing the set of density zero for the series $\dfrac{1}{n}\sum_{k=0}^{n-1}a_k^2$ instead, and use it to characterize (1).
Is my reasoning correct or am i missing something that is obvious?
Answer: $a_n \to 0$ through $J^{c}$ (which means $n$ is restricted to integers not in $J$) iff $a_n^{2} \to 0$ through $J^{c}$ and this gives the equivalence. [You have apply the characterization both the sequences $(a_n)$ and $(a_n^{2})$. You can  take the same $J$ for both of these because union of two sets of density $0$ has density $0$].


How to implement Master details classes find function in JavaScript?

Question: I have this code:
function Item(id, itemType, itemData, itemCategoryId, itemRank) {
    this.id = id;
    this.itemType = itemType;
    this.itemData = itemData;
    this.itemCategoryId = itemCategoryId;
    this.itemRank = itemRank;
}
function Category(id) {
    this.id = id;
}

And I want to write a function for the Item class which I give it the CategoryId and it will return all items objects with this Category id.
What's the best way to do that?
Answer: I see no array....
I would assume that there would be an items prototype (note that there are no classes in javascript), and it would look something like this:
function Item(id, categoryId, data, rank) {
  this.id = id;
  this.categoryId = categoryId;
  this.data = data;
  this.rank = rank;
}

function Items() {
  this.items = [];
  this.findByCategory = function(categoryId) {
    var result = [];
    for(var i=0;i<this.items.length;i++) {
       if (categoryId == this.items[i].categoryId)
          result.push(this.items[i]);
    }
    return result;
  }
  this.add = function(id, categoryId, data, rank) {
    this.items.push(new Item(id, categoryId, data, rank));
  }
}

var items = new Items();
items.add(2, 0, null, null);
items.add(1, 1, null, null); // I'm not going to care about data and rank here
items.add(2, 1, null, null);
items.add(3, 1, null, null);
items.add(4, 2, null, null);
items.add(5, 3, null, null);

var cat1 = items.findByCategory(1);
alert(cat1); // you will get a result of 3 objects all of which have category 1


Views... no format options in Fields->User?

Question: In any Field using the USER type there are no format options.  I'm making a user_picture view and want to use the image cache option.  But, at the bottom of any Field (pertaining to USER) where Format* usually shows up, it's not there.  Any ideas why?  Thank you.
Also, Format* works for nodes/content types.  So, it's installed and working functionally.
Answer: The short answer is that the user image is not a field unlike images attached to nodes. Views is using the field formatter that applies to fields and the way they are themed to allow you to select how you want to theme the field. This functionality doesn't work for properties like the user image.
The same goes for the say the node type. You can't select how to display the node type.
The easiest thing to do, is properly get the raw url and with theming turn it into the image with the image cache preset you want to use.
Comment: Thanks for the response.  I tried the old picture, $alt, $title,  $attributes); ?> in my comment.tpl.php but it won't render.  I even tried just:  picture ?> and that would't render.  Any ideas on this?  Thank you.
Comment: @Graham Sounds like the account does not have a profile picture or it hasn't been loaded, try doing a user_load on inspect the $account variable.


About the multiplication map $I\otimes M\rightarrow M$

Question: so I am learning about flat modules and I found this criterion for flatness. An $R$-module $M$ is flat iff for every finitely generated ideal $I$, we get that the multiplication map $I\otimes_R M\rightarrow M$ is an injection (Eisenbud Proposition 6.1)
I am confused because say we have any $M$ (an $R$ module), and say that $i\otimes m\mapsto 0$. This means that $im=0$, but wouldn't this imply that $i\otimes m=1\otimes im=1\otimes 0=0$, so the kernel is trivial, and hence the map is injective always?
I am obviously doing something wrong, so I'd appreciate anyone that could clarify things a bit!
Comment: Also: Not every element of the tensor product is a pure tensor. The elements are sums of these.
Answer: You can't write $i\otimes m=1\otimes im$ unless $1\in I$, i.e., unless $I=R$.
Comment: Thanks. That was very dumb of me.


Smarty (& Codeigniter): What is current path?

Question: This is my first time playing with CI & Smarty, and I am a trying to build a relative URI so I can load a JS file.
I took a guess at the appropriate path to use for importing the little js plugin, and can use some guidance.
I dropped the plugin into www/js, and since all initial calls go through www/index.php,  my first attempt was simply src='js/blah/blah/blah.js'.
If there is a way to echo the path from a TPL, I figure that would give me enough info.
Is this info avail in Smarty?
Is there a better way to achieve my intended goals (loading a JS file) ?
Comment: See [`base_url`](http://codeigniter.com/user_guide/helpers/url_helper.html)
Answer: When loading resources in an html file (js, css, images, etc.), you are better off using absolute paths. It is the browser that is requesting these resources and not CI or Smarty, so I would just use:
/js/blah/blah/blah.js

Where your root is the web-server root (www/ in your example).
Comment: Hmmm, thanks .. That is EXACTLY what I expected .. I wonder why it's not working .. Maybe I'll re-comb for type-o's or something.  ???
Comment: For some reason, I just couldn't get that going .. so I simply plopped the plugin onto our live public-facing server, and used that URI instead. (which is working fine, BTW)
Comment: @mOrloff Very strange, is perhaps CI rewriting the paths?


Inserting a specific row multiple times in VBA

Question: Our clients want their excel sheets formatted to where a new header (The entire '1' row) to be inserted above the last value whenever a new value in column 'A' is present
Essentially I am copying row '1' and inserting it whenever I find a new value in column 'A'
Here is the sub I am using to format it, but it just keeps looping and crashes.
Sub insertHeader()

Range("A2").Select

Do Until ActiveCell.Value = ""

    If ActiveCell.Value = ActiveCell.Offset(1, 0) Then

        ActiveCell.Offset.Select

    Else

        Range("A1").EntireRow.Insert
        ActiveCell.Offset.Select

    End If

Loop

End Sub

Comment: what have you tried to find the error? Does this Loop should move from row to row until a cell is empty?
Answer: You have to tell Offset how and where to offset. As in Offset(row offset, column offset):
ActiveCell.Offset(1,0).Select

Oh, and also your copy, man... Ok, here is the code:
range("a3").select
Do Until ActiveCell.Value = ""

  If ActiveCell.Value <> ActiveCell.Offset(-1, 0).Value Then
  'comparing it upwards, as the standard insert will insert a row above your active cell.

    ActiveCell.EntireRow.Insert
    Range("a1").EntireRow.Copy ActiveCell
    ActiveCell.Offset(1, 0).Select
     'move on to the row I was at before inserting a new row

  End If
  ActiveCell.Offset(1, 0).Select
Loop

Comment: Awesome Possum. Man, can't believe I missed that offset and my logic was flawed. Thank you so much.


devise_invitable does not send emails

Question: it is the first time using devise_invitable gem
,there is no error and no emails sent
projects_controller.rb
def add_admin
      @email = :email
      User.invite!(:email => @email, :project => current_user.project)
  end

views/projects/show.html.erb
<% if @project == current_user.project %>
  <% @user = User.new %>
  <%= "you can add admin to " + @project.project_name %>

 please type his email

  <%= form_for @user, url: {controller: "projects", action: "add_admin"} do |f| %>
    <%= f.email_field "email" %>
    <%= f.submit "Invite" %>
  <% end %>
<% end %>

routes.rb
post "/projects/add_admin"

Comment: Maybe you just never jump into the if execution block: try this: <% if @project.id == current_user.project.id %>
Comment: Have you set up your mailer properly? Try sending and receiving mails manually first.
Comment: it sends email while user registration normally.
Answer: Finally i found it
the method should be
  def add_admin
      User.invite!(:email => params[:user][:email], :ProjectId => current_user.project.id)
  end

devise_invitable does not send emails