Will learning guitar tabs help me improve at learning other tabs/playing melodies?

Question: I want to know if by learning a song from a tab I'll somehow get better at learning a different song.
I have this feeling that by learning a song from a tab I'll only succeed at learning that one song. This inkling has caused me to avoid learning any tabs up to this point and just focus on chords, learning the names of the notes for the frets, and try learning scales so I can sight-read sheet music.
I can read sheet music but obviously it's not as simple as just being able to read it when it comes to the guitar. All the same, sight-reading sheet music is a transferable skill, whereas I'm not sure about reading a tab. Will I be starting over for each tablature?
Maybe what I'm asking is: Is it possible to sight-read tabs?
Just as clarification, after posting this question I realized my main concern was not knowing how to lay out my left hand fingers when playing tabs, as they usually don't indicate finger position. This concerned me because I felt that by not having a method for knowing which fingers to use learning a tab would not be transferable to another tab because I would pretty randomly choose which fingers to use on the next tab and so the order would be different, etc. After realizing the crux of my concern, I found this post which has allayed my fears remarkably.
Thanks for all the answers, and sorry for not being clear!
Comment: Why do you thinking reading one kind of notation is so different?  Practising something always helps you improve (barring things like "practising wrong" or reaching physical limits).
Answer: Sight-reading tabs, and by that I mean playing the tab off the paper is something one learns quite faster than learning to play a regular score from paper.
That's the reason for their existence.  They are basically a pre-prepared performance.
Reading tabs without having an instrument in hand and figuring out what the music is in your head works worse than with a regular score.
The guitar is essentially a polyphonic instrument.  That means that for sightreading you cannot afford even mild mental contortions: the fingers need to basically work directly off the score.  With a regular score, the score/string/finger connection basically has to be established for every key signature anew.  A tab is much more direct.
But the key signatures and intervals carry musical meaning, so that's what you want to be reading when analyzing music.
I'd not stay away from tab like the plague, but it makes good sense to spend more time with regular scores, since mastering those needs more time, but it's an important skill.
Comment: It's also worth noting that tablature affords some things specific to guitar that are not typically present in sheet music, like specific notations for hammer-ons, pull-offs, slides, pull-off-slides, so on and so forth, so one can make an argument that while it is of utmost importance to understand music theory and be able to read scores, reading/writing tablature is actually better suited for guitar as an instrument.  Plus, probably a majority of guitarists in popular music only know tablature, so that is what you will have to know if working outside of classical.
Answer: The short answer to your question is yes - it is possible to sight read tabs.  At least for folks who seem to prefer tabs over standard musical notation.
I have a friend who after years of piano lessons decided to learn to play guitar.  Her guitar teacher writes her lessons in tab.  She has learned to sight read tab but has expressed that she wishes he would write the lessons out in standard notation so she will also be learning the names of the notes she is playing.
Tablature is like musical shorthand for folks like myself, who don't want to spend the time learning the names of the notes I am playing but prefer to just know which string and which fret.  I really don't care what the note I play is called.  I just want to play the correct note at the right place in the song (so it sounds like the song) and that works for me.
Tabs show you were to play the note but don't tell you what the note is.  Standard music notation on a 5 line staff shows which notes to play - but then you must know where that note is on your guitar.
So I would venture to say that if you started relying on tab to the exclusion of sheet music, it would hinder your ability to learn to recognize where each note was on the guitar fretboard. But learning an occasional song by using tab, probably won't hurt you.
Comment: One can read tablature and know the "notes" they are playing just as easily as reading notation; but tablature is more expressive as a writing format for guitar (and bass guitar) specifically, allowing for instrument-specific actions like slides and hammer-ons.  You still have to know the "notes" whether you are looking at a scale or a tab; that is just related to level of musicianship.
Comment: @rcd  I disagree with you about needing to know the notes with tab.  I can read tab just fine.  I have no idea what the names of the notes are.  The tab tells me which string and which fret to play.  I can't tell from that which note I am playing (and it's not important to me).  Tabs also cannot visually convey the direction of the melody like notes can.  Reading standard music notation you can tell where the melody is going up or down in pitch.  Not so for tabs unless you read the numbers and take into account which string you are on.  You can figure it out with tab but it's not intuitive.
Comment: What I meant was that neither a tab nor score spells out for you what note or chord you are playing–you must know that by reading music in general.  Sure, one can play a tab and have no idea what notes they are playing, but I was referencing the OP vs your post (they suggest a music theory background, you suggest a hinderance). If one wants to play guitar, reading tablature is a great way of reading notation (since it provides instrument–specific notations), but one must ultimately know the notes on the fretboard, piano, etc, whether reading score or tabs, especially to transfer/collaborate.
Comment: @rcd I will agree that it would be very helpful to know the notes on the fretboard if I wanted to transfer/collaborate.  But I feel zero need to learn the notes on the fretboard to compose melodies for my original songs, perform originals or covers, or just play for my own enjoyment.  I record my arrangements and the recording software captures the notes (whatever they happen to be) which allows me to share my melodies with others.  But I still don't know or feel a need to know - the names of the notes.  Been playing guitar quite a long time and will continue without ultimately knowing notes.
Answer: To answer your question: yes, of course. The point is tablatures are simpler at the beginning of your friendship with guitar, because it doesn't force you to learn traditional notation for many hours. Usually, guitarists are not patient enough to spend many hours first on learning theoretical stuff. So if you've just began playing guitar, use tablatures, and as you improve your technical and musical skills, you can check if standard notation is something you really need.
In fact, the main question is always whether you want to know notes names because you need them, or it is just ars gratia artis. Some musicians can say, that you won't be a musician if you can't name note you play. Personally I believe the most important thing is that you're aware what are you playing in the musical and not necessarily in mathematical sense.
Answer: In my experience both tabs and notation are useful. I can sight read notation faster and yet tab is more enjoyable and my brain is drawn to it. Tab wont prevent you from learning the tougher skill of reading notation. Also you can learn to sight read tablature. I have seen some people do it really fast.
On the other hand, there is also extra knowledge hidden in notation for experienced players to gain an advantage not just in speed but in range or possibilities, musical learning and growth.
I say learn both, but don't be afraid of learning either, or in any particular order.
Answer: It all depend on your long term goals. I doubt tabs will help with music theory, understanding harmonisation etc.
If you want to write music in the future I'd try to at least learn basic standard notation to analyse harmony and understand what you are playing instead of mereley repeating what you hear.


Selects dependentes em PHP

Question: Tenho dois selects, sendo o segundo select totalmente dependente do primeiro. Gostaria de realizar o filtro, mas não estou conseguindo visualizar uma solução. Alguém poderia me ajudar?

            <select name="rTecn" onChange="document.formFilter.submit();">
                <option value="">[ Todas as tecnologias ]</option>
                <?php
                    $TECN = getTecnologias();
                    while ($TECNOLOGIA = mysql_fetch_array($TECN)) {
                ?>
                <option value="<?php echo $TECNOLOGIA["TECNOLOGIA"]; ?>" <?php echo ($TECNOLOGIA["TECNOLOGIA"] == $rTecn) ? 'selected' : '' ?>><?php echo $TECNOLOGIA["TECNOLOGIA"]; ?></option>
                <?php
                    }
                ?>
            </select>

            <select name="rForn" onChange="document.formFilter.submit();">
                <option value="">[ Todos os fornecedores ]</option>
                <?php
                    $conexao->setSQL("SELECT * FROM tab_aro_pcd_riscos, tab_aro_pcd_fornecedores WHERE aro_riscos_mfir = aro_forn_mfir GROUP BY aro_forn_mfir ORDER BY aro_forn_nome ASC");
                    $resultado = $conexao->Consultar();

                    while ($forn = mysql_fetch_array($resultado)) {
                ?>
                <option value="<?php echo $forn["aro_forn_mfir"]; ?>" <?php echo ($forn["aro_forn_mfir"] == $rForn) ? 'selected' : '' ?>><?php echo $forn["aro_forn_mfir"] . " - " . $forn["aro_forn_nome"]; ?></option>
                <?php
                    }
                ?>
            </select>

Comment: Qual é o erro que está acontecendo? Não entendi.

Observação: Esse código tem uns 10 anos? Register Globals  tornou-se OBSOLETA desde o PHP 5.3.0. Confiar nesta funcionalidade é altamente não recomendado.
Comment: Confesso pra você que o código é bem antigo. Na verdade estou dando manutenção nele e uma atividade para atualização ja foi requerida
Comment: Em relação ao erro, na verdade eu gostaria que as informações do segundo select fossem refletidas com base na escolha do primeiro filtro
Comment: No segundo select você deve adicionar o valor de `$rTecn` ao where da sql  para trazer apenas os fornecedores  relacionados à tecnologia selecionada. Existe esse relacionamento entre tecnologia e fornecedor no seu banco de dados?
Answer: Faça uma consulta por ajax para pegar os dados de acordo com o o id selecionado.

            <select name="rTecn">
                <option value="">[ Todas as tecnologias ]</option>
                <?php
                    $TECN = getTecnologias();
                    while ($TECNOLOGIA = mysql_fetch_array($TECN)) {
                ?>
                <option value="<?php echo $TECNOLOGIA["TECNOLOGIA"]; ?>" <?php echo ($TECNOLOGIA["TECNOLOGIA"] == $rTecn) ? 'selected' : '' ?>><?php echo $TECNOLOGIA["TECNOLOGIA"]; ?></option>
                <?php
                    }
                ?>
            </select>

            <select name="rForn" onChange="document.formFilter.submit();">
            </select>

arquivo.php
<?php
$id = isset($_GET['id']) ? $_GET['id'] : null;
$conexao->setSQL("SELECT * FROM tab_aro_pcd_riscos, tab_aro_pcd_fornecedores WHERE aro_riscos_mfir = ".$id." GROUP BY aro_forn_mfir ORDER BY aro_forn_nome ASC");
$resultado = $conexao->Consultar();
$html = '<option value="">[ Todos os fornecedores ]</option>';
while ($forn = mysql_fetch_array($resultado)) {
    $html .= "<option value='".$forn['aro_forn_mfir']."' ".$forn['aro_forn_mfir'] == $rForn ? 'selected' : '' .">".$forn["aro_forn_mfir"] . " - " . $forn["aro_forn_nome"]."</option>";
}
echo $html;
?>

Selects dependentes em PHP


External Tangents of Circles.

Question: If we have three circles C1 C2 C3. Consider the intersection between the external tangents of each pair of circles . Show that the three points of the intersections are collinear.
Is this a well known theorem on its own?
Comment: @JackD'Aurizio That could be an answer...
Answer: It is known as Monge's theorem. On the wikipedia page you can also find different proofs.

External Tangents of Circles.


Einstein Tensor Notation: Addition inside a function

Question: Main Question
Can I represent addition of multi-dimensional variables in this linear function in Einstein Summation Convention?
$$
f(\mathbf{x} + \mathbf{v})
$$
This didn't seem right $f(x_{\mu}+v_{\mu})$ and nor did $f(x+v)_{\mu}$
More Information...
I am doing an unrelated question on multi-dimensional Taylor Series and I wanted to test my knowledge of compact tensor notation.
My full expression is
$$
   f = f(x_1,\cdots,x_N) = f(\mathbf{r})
   \quad\text{and}\quad
   \mathbf{v} = \left(h_1,\cdots,h_N\right)
   \\
   f( \mathbf{r} + \mathbf{v} ) =
   \mathbf{v} \cdot \nabla f( \mathbf{r} )
   + \sum^{N}_{n=2} \frac{1}{n!} \left( \mathbf{v} \cdot \nabla \right)^n
   f(\mathbf{r}) + R_N ( \mathbf{r}, \mathbf{v})
$$
I am looking to compactly represent this in tensor notation as I am sure it can be done.
Comment: $f(x+v) = f((x^\mu + v^\mu)e_\mu)$. Einstein notation works only when you are given a basis. Here that basis is $e_\mu$.
Comment: btw what is this $f$ exactly? $f$ from where to where? I assume $f$ is linear?
Answer: With tensor notation I assume you just mean Einstein's summations convention, i.e. the convention where repeated indices are summed over all the coordinates instead of having an explicity sum: $a_ib_i \equiv \sum_{i=1}^n a_i b_i$.
The notation $f({\bf x})$ is just a shorthand for $f(x_1,x_2,\ldots,x_n)$, i.e. to tell the reader that $f$ takes points in $\mathbb{R}^n$ as it's argument. The point $(x_1,\ldots,x_n)$ can be written as the sum $x_\mu e^\mu$ where $e^\mu$ are basis-vectors in $\mathbb{R}^n$, for example $e^\mu=(0,\ldots,0,1,0,\ldots,0)$, however writing $f(x_\mu e^\mu)$ is not standard and can be confusing. You are better off using one of the two standard ways mentioned above with $f({\bf x})$ being the most compact one.
The summation convention is often very useful when doing calculations, the final result of such calculations often has a more clear and compact formulation using vector-calculus expressions like $\nabla$, dot-product, $\times$, etc. The notation should be used wisely. Personally I think the formula you have looks better as written than expressed in the summation convention (i.e. ${\bf v}\cdot \nabla f$ is more clear and compact than $v_i\frac{\partial f}{\partial x_i}$) and also note that the sum $\sum_{n=2}^N$ cannot be removed even when using the summation convention (without additional definitions).
Comment: Thanks for a brilliant, well rounded answer. Despite being able to use these constructs in complex topics such as RQFT, often with the pace of new concepts being introduced I do not have time to apply the concepts in unusual formats. Hence the confusion as you see here! May I ask how you would you represent a Hessian of $(\mathbf{v}\cdot\nabla)^n$ (in its own right). Would this be correct $v_i\partial_i\partial_jv_j$ with the assumption that $i,j=1,\cdots,n$
Comment: Ok I see my error. Also it is clear why it may as well be left in the brackets
Comment: @AlexanderMcFarlane For $n=2$ we have $[{\bf v}\cdot \nabla]^2 \equiv v_iv_j \frac{\partial^2 f}{\partial x_i\partial x_j} = v_i v_j H_{ij}$ where $H$ is the Hessian of $f$. Some also use the notation $\partial_{i}\partial_{j}f \equiv \frac{\partial^2 f}{\partial x_i\partial x_j}$ (note that $v_i$ are constants here so they do not get differentiated and can be moved to the left).
Answer: After discussion with a few course mates we came to the conclusion that it should generally be left as the following,
$$
f(\mathbf{x} + \mathbf{v}) = \cdots
$$
with index notation on other relevant terms.
On the topic of taylor series for tensors there is a really interesting treatment of Taylor's Theorem in Tensor Calculus presented in this 1929 paper.
Comment: So, an unclear question with a pointless answer. And you present downvotes as an evidence of unfriendliness.
Comment: Please keep meta comments on meta. Please explain how if someone is unsure if they can represent $f(\mathbf{x}+\mathbf{v})= \cdots...$ in tensor notation that this is then completely useless.


Separate panels variants for 'edit' & 'add' nodes of same type

Question: [D7/Panels 3]
I have two different panels layouts - one for editing, the other for adding nodes of the same content type ("Contact Details").
A panel page for overriding 'edit' pages exists in Panels (in code), which I have activated. I've made a variant which works for 'edit' pages, but it is also overriding the 'add' page with the same layout.
I've added a context of 'Node add form' with 'Contact Details' as the 'Node type'. Also added a selection rule:
Node: type / Node add form is type "Contact Details"
Both forms still appear in the same panel layout (the one for 'edit' pages).
Help much appreciated :)
Answer: Try using String: URL path in variant Selection Rule.
Edit path: "node/*/edit"
New path: use your content type path (node/add/your-content-type)


get immediate child node of a parant node of an xml file using powershell

Question: I have an xml file like given below
 <ParentNode>
   <childnode1>
    <Name string="Code1"/>
   </childnode1>

   <childnode2>
    <Name string="Code2"/>
   </childnode2>
   <childnode3>
    <Name string="Code3"/>
   </childnode3>
</ParentNode>

how can i print all the child nodes of ParentNode using powershell
i tried by using given code
foreach($child in $xmlfile.ParentNode)
{
Write-Host $child
}

it should print
childnode1
childnode2
childnode3

Answer: PS>[xml]$x=gc c:\temp\xml.xml
PS>$x.ParentNode

or maybe you want :
PS>$x.ParentNode |gm -MemberType property |select -expand name
childnode1
childnode2
childnode3


Law of total expectation and conditioning without including all relevant information

Question: According to the law of total expectation (or iterated expectations), it is true that $E(A|B)=E(E(A|B,C)|B)$.
Why this is not equal to $E(A|B)=E(E(A|C)|B)$?
Why is it important that the first set of information is included in the second one? Can you provide an example to illustrate how important this mistake can be?
Answer: Intuition
Intuitively, $E(A \mid C)$ marginalizes over all information about $A$ that is not contained in by $C$ - including such information that is contained in $B$ but not in $C$. When we take the conditional expectation of $E(A \mid C)$ conditional on $B$, we don't get this  "information given only by $B$" back.
To get a simple counterexample, let us take this idea into the extreme and consider a case where $B$ contains all information about $A$ (i.e., tells us the value of $A$) while $C$ contains no information about $A$.
A counterexample
Counterexample: let $A=B$ (with probability 1) and  $A$ and $C$ be independent.
Then, we have
\begin{equation}
E(A\mid B) = E(B\mid B)= B = A
\end{equation}
However, applying the independence of $A$ and $C$,  of the second equation is
\begin{equation}
E(E(A \mid C) \mid B) = E(E(A) \mid B),
\end{equation}
and since $E(A)$ is a constant,
\begin{equation}
=E(A).
\end{equation}
In general $A$ is not equal to $E(A)$ and thus this shows the second equation in the question is not valid.
Connection of the counterexample to the intuition
Indeed, the results of the counterexample agree with the initial intuition: $B$ carries full information about $A$, thus $E(A\mid B) = A$. Meanwhile, $C$ carries no information about $A$ and thus all this information is lost when taking the expectation conditional on (only) $C$. Therefore, $E(E(A\mid C) \mid B)$ is just $E(A)$, the "prior" expectation of $A$ without conditioning on any extra information.


How to Select All checkboxes in Flex Item Renderer?

Question: I am stuck at a point where I need to select all check boxes of the Item Renderer.
I have a Select All button on whose click my all check boxes needs to get selected. Is it possible to do in Flex item renderer.
Below is my code for item renderer:

                          rowCount="2" columnCount="5" dragEnabled="false" dragMoveEnabled="false" height="100%"  width="100%" verticalScrollPolicy="on" verticalScrollPosition="0" selectable="false">

<mx:itemRenderer>

                        <fx:Component>

                            <mx:VBox width="175" height="200" verticalGap="0" verticalScrollPolicy="off" horizontalScrollPolicy="off" >

                                <fx:Script>

                                    <![CDATA[
                                        import mx.collections.ArrayCollection;
                                        import mx.controls.Alert;
                                        import mx.controls.List;
                                        import mx.core.FlexGlobals;
                                        import mx.utils.ObjectUtil;

                                        [Bindable]

                                        public var productData:Array = new Array();

                                        import mx.collections.ArrayCollection;
                                        import mx.controls.listClasses.BaseListData;
                                        private var _listData:BaseListData;
                                        private var _tileList:List;
                                        [Bindable("dataChange")]
                                        public function get listData():BaseListData
                                        {
                                            return _listData;
                                        }
                                        public function set listData(value:BaseListData):void
                                        {
                                            _listData = value;
                                            _tileList = value.owner as List;
                                        }
                                        override public function set data(value:Object):void
                                        {
                                            super.data = value;
                                            checkFileToDownload.selected = value["isSelected"];
                                        }
                                        private function onChange(event:Event):void
                                        {
                                            data["isSelected"] = checkFileToDownload.selected;
                                            FlexGlobals.topLevelApplication.checkFileToDownload(event);
                                        }

                                        /* protected function checkSelectedFile(event:MouseEvent):void
                                        {
                                            // TODO Auto-generated method stub

                                                checkFileToDownload.selected = true;

                                                FlexGlobals.topLevelApplication.generateDownloadFileArray("push",checkFileToDownload.name,checkFileToDownload.automationName);
                                                outerDocument.downloadButtonStatus(event)

                                        } */

                                    ]]>

                                </fx:Script>

                                <mx:HBox id="currentTileElement">

                                    <s:CheckBox id="checkFileToDownload" name="{data.itemUrl}"  automationName="{data.contentId}"
                                                change="{onChange(event)}"
                                                skinClass="com.skinClass.CustomCheckBoxSkin" click="{outerDocument.downloadButtonStatus(event)}"/>

                                    <mx:TextArea wordWrap="true" fontWeight="bold" text="{data.title}" borderStyle="none"  verticalScrollPolicy="off"

                                                 horizontalScrollPolicy="off" textAlign="left" editable="false"/>

                                </mx:HBox>

                                <mx:HBox>

                                    <mx:Image  source="{'/assets/'+data.contentId.substring(1, 2)+'.png'}" maintainAspectRatio="true"/>

                                    <mx:Image id="tileListImageSource" width="150" height="75" maintainAspectRatio="false"

                                              source="{data.localActualPath}"/>

                                </mx:HBox>

                                <mx:VBox  horizontalGap="0" width="100%" verticalGap="0" paddingLeft="25">
                                    <s:Spacer height="2"/>

                                    <mx:TextArea text="{data.author.split('|')}" color="#FF9900" fontWeight="bold" chromeColor="white" height="40" editable="false" wordWrap="true" borderStyle="none" verticalScrollPolicy="on" horizontalScrollPolicy="off" textAlign="left"/>

                                    <s:Spacer height="2"/>
                                    <mx:Text fontSize="11" text="{data.publishedDate}"/>
                                    <s:Spacer height="2"/>
                                    <mx:HBox horizontalGap="0" verticalGap="0">
                                        <mx:Text fontWeight="bold" fontSize="10" text="File Size: " paddingRight="0"/><mx:Text fontSize="10" color="red" paddingLeft="0" fontWeight="bold" text="{data.itemSize}MB"/>
                                    </mx:HBox>
                                </mx:VBox>
                            </mx:VBox>

                        </fx:Component>

                    </mx:itemRenderer>

                </mx:TileList>

Any help is appreciated.
Thanks,
Ankit Tanna.
Comment: I only see one checkbox in your itemRenderer code.  You can check it by doing `checkFileToDownload.selected = true` .  Did you mean you to ask how to select all checkboxes in a DataGrid or List that makes use of this itemRenderer?
Answer: You can affect all the checkboxes in your list by changing a property in the dataprovider;s objects and binding to that.  Something like this in your click handler:
public function selectAllBtnClickHandler(e:MouseEvent):void {
  if (selectAllBtn.selected) {
    for each (var value:Object in checkboxList.dataProvider) {
      value["isSelected"] = true;
    }
  }
}

Then change your checkbox declaration as follows:
<s:CheckBox id="checkFileToDownload" name="{data.itemUrl}"  automationName="{data.contentId}"
change="{onChange(event)}" selected="{data.isSelected}"
skinClass="com.skinClass.CustomCheckBoxSkin" click="{outerDocument.downloadButtonStatus(event)}"/>

Answer: I want to clear the concept of Brian a bit , so that you can understand it better.
Here is an array collection i am using to populate the grid below
[Bindable] private var testArray:ArrayCollection = new ArrayCollection
            (
                [
                    {NAME:'Alan',DEPT:'CIS',ADDRESS:'dhaka',chk:0},
                    {NAME:'Jordan',DEPT:'CIS',ADDRESS:'dhaka',chk:1},
                    {NAME:'Simmi',DEPT:'CIS',ADDRESS:'dhaka',chk:0},
                    {NAME:'Alex',DEPT:'CIS',ADDRESS:'dhaka',chk:1},
                    {NAME:'Adams',DEPT:'CIS',ADDRESS:'dhaka',chk:0}
                ]
            );

here goes the code of datagrid
<mx:DataGrid height="100%" width="100%" id="dataGrid" dataProvider="{testArray}">
        <mx:columns>
            <mx:DataGridColumn headerText="Name" dataField="NAME"/>
            <mx:DataGridColumn headerText="Department" dataField="DEPT"/>
            <mx:DataGridColumn headerText="Address" dataField="ADDRESS"/>
            <mx:DataGridColumn headerText="Address" dataField="chk">
                <mx:itemRenderer>
                    <fx:Component>
                        <mx:CheckBox selected="{data.chk==1?true:false}"/>
                    </fx:Component>
                </mx:itemRenderer>
            </mx:DataGridColumn>
        </mx:columns>
    </mx:DataGrid>
<mx:Button label="Check All" click="button1_clickHandler(event)"/>

Notice the item renderer which is a check box is looking on the value of "chk". You can make all the check boxes "CHECKED" by clicking "Check All" button. here is the "button1_clickHandler" function
protected function button1_clickHandler(event:MouseEvent):void
        {
            for(var i:int=0;i<testArray.length;i++)
            {
                testArray[i].chk = 1;
            }
            testArray.refresh();

        }

Comment: +1 - This is a nice concrete demonstration of unifying part of the view state with the data model.


How to require a user to be logged in to access files

Question: On my website I currently have a way for users to upload files.  It has been brought to my attention that these files are showing up in search engines.  I'm fairly new and this is not a desired effect.  As a way to fix this for now, is there a way I can restrict access to sites/default/filesto logged in users? Thanks!
Answer: You have to setup the private file system. You can do this on /admin/config/media/file-system.
Next you will have to alter your field to use the private file system instead of the public file system. If this field already has data, you can use https://www.drupal.org/project/filefield_paths to migrate the files from public to private
Answer: Go to admin -> Config -> Media -> file system. Ensure that a folder for the private file system is set. Then go to the file upload element settings, and choose the private method for file storage.


Enviar dados do RecycleView para Activity

Question: Bem, sou nova no desenvolvimento Android e gostaria de saber como passo o valor da opção selecionada no Recycleview para um EditText que está em outra Activity
Comment: Tente formular melhor a sua pergunta, colocando código do que você já tem feito e onde está tendo dificuldades. Assim, fica mais facil alguem se dispor a te ajudar.
Answer: Existem diversas maneiras de fazer isso. Primeiro você precisa receber o evento de clique no RecyclerView na Activity atual e depois você pode passar esse valor no Intent para uma outra Activity.
Para detectar o evento de clique em um item da RecyclerView você pode criar um listener dentro do seu ViewHolder e utilizar uma interface para comunicar de volta os dados para a Activity
Aqui está um exemplo do adapter da RecyclerView
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
    private List<String> items;

    // Referência para o listener obtido no 'setOnClickListener'
    private OnItemClickListener clickListener;

    public ItemAdapter(List<String> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        // Aqui você infla o layout de cada view
        return new ViewHolder(null);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        String item = items.get(position);

        viewHolder.bind(item);
        // Aqui você faz o bind entre a view e o item da lista atual
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    // Método utilizado para comunicar o evento de clique de volta para a Activity
    public void setOnClickListener(OnItemClickListener onClickListener) {
        this.clickListener = onClickListener;
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        String item;

        ViewHolder(@NonNull View itemView) {
            super(itemView);

            // Criando o evento de clique no item da lista e repassando o evento de volta para o listener
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickListener.onItemClick(item);
                }
            });
        }

        void bind(String item) {
            this.item = item;
        }
    }
}

// Interface utilizada para criar o contrato entre Adapter/Activity
interface OnItemClickListener {
    void onItemClick(String item);
}

E você faria isso na Activity:
List<String> items = new ArrayList<>();

        ItemAdapter adapter = new ItemAdapter(items);

        adapter.setOnClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(String item) {
                // Agora você tem o item clicado e pode mandar ele para outra Activity

                Intent intent = new Intent(MainActivity.this, OutraActivity.this);
                intent.putExtra("item", item);
                startActivity(intent);
            }
        });

Outro link para referência: https://stackoverflow.com/questions/24471109/recyclerview-onclick


Views Autocomplete search multiple values

Question: I'm trying to have a search filter that searches on 2 values and works with autocomplete list.
This is what I've done:

Installed the module Views filters populate.
added two filters "CNK" and "Naam" (both not exposed) and added them to a OR filter group. I used the operator "Contains any word" for both fields.
Created a filter "Global: populate filters", added the two fields into this and exposed it.

My filter criteria looks like this:

But I don't have the option for autocomplete. How can I do this the best way?
Answer: You can use Views autocomplete filter module to have auto-complete feature on views exposed filters.

It works for node titles or cck text fields.
The autocomplete results are actually the view results, so they are
  view related.

Check out this Demo video.
Comment: I'm using the views autocomplete filter but it doesn't work on the global: populate filters. It doesn't show the option autocomplete.
Comment: follow this post, :)

https://drupal.org/node/451000
Comment: and also this, http://drupal.stackexchange.com/questions/42726/expose-single-filter-of-combination-of-two-fields-in-views/43762#43762
Comment: I've done the steps in the last link you gave me (as you can see in my topic) but I don't have an autocomplete option on my global filter that selects the other 2 fields ... I need autocomplete on that field ..


Probability with a hundred coins

Question: I have a question.
If a Hundred coins are tossed at the same time what are the total number of possibilities, and what is the probability of getting tails on all the coins?
Could anyone answer it?
Thanks!
Comment: there are $2^{100}$ different outcomes of coin which result in $100$ different configurations. The probability of getting tails on all the coins is $1/2^{100} \sim 7 \cdot 10^{-31}$. It's *very* small
Comment: Why hundred? To develop some intuition do it with a very small amount of coins. Then project that on bigger or indeterminate amounts.
Comment: @Ant: $101$ different configurations
Comment: @Henry true that! thanks
Answer: Maybe you could start with $N=3$ coins, instead of $100$, for instance.
For $3$ coins, the situation is simple to understand : you have $2$ possibilites for the first coin (head and tail), $2$ possibilites for the second coin, and $2$ possibilites for the third coin (these are supposed to be independant events). Then, you get $2 \cdot 2 \cdot 2 = 2^3 = 8$ possibilities. You can even do the list (H = head, T = tail) : $HHH, HHT, HTH, $ and so on.
For $N=3$, the probability of getting tails on all the coins is then $1/8$.
I hope you can "generalize" to $N=100$.
Comment: Starting with less coins is a good advice.
Answer: Total ways are $2^{100}$ heads or tails for each coin and way where all are tails is $1$ so probability is $1/2^{100}$
Answer: You can model the toss as a tupel with $100$ binary values, so there are $2^{100}$ possibilities. The sought chance is one of those $p=2^{-100}$.

Probability with a hundred coins


Calcular raiz cúbica

Question: Estou a ter dificuldade a criar os seguintes botões Raiz cubica e LN.
Tenho botões que devem ser muito parecidos como por exemplo a raiz quadrada normal e o log.
Tentei criar o seguinte para a raiz cubica:
   private void btn_raizcub_Click(object sender, RoutedEventArgs e)
    {
        primeiro += double.Parse(janela.Text);
        resutado = Convert.ToSingle(Math.Sqrt(primeiro/3.0));
        janela.Text = resutado.ToString();
    }

Comment: E qual é a dúvida?
Comment: Pelo menos a raiz cúbica não está a funcionar correctamente dessa forma. Apesar de funcionar
Comment: Não me dá correcto nem com Sqrt nem com o Pow
Answer: A fórmula correta para obtenção da raiz cúbica é:
Pow(primeiro, 1.0/3.0)

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Note que esse double.Parse() pode falhar, eu não usaria desta forma, o TryParse() é mais adequado. É meio estranho criar um tipo de dupla precisão e usar um Convert.ToSingle().

Calcular raiz cúbica


Calling an Intent from the adapter maybe by InterationListener

Question: I was told that it is better to start another activity from the main activity instead of starting it from the adapter and that I should use an InteractionListener to communicate with the adapter and call the intent from the main activity.
Problem is I didn't understand how to implement an InteractionListener.
I tried this https://developer.android.com/training/basics/fragments/communicating but I don't know how to initialize the callback.
I tried to do this as I was told but I'm beginner and didnt understand this tutorial, got some errors I couldnt solve.
interface OnAdapterInteractionListener {
    fun itemSelected(/Some Parameters Maybe/)
}

class ItemRecyclerViewAdapter(
    private val mListener: OnFragmentInteractionListener?
) :  {
    // set on click listener from item to OnAdapterInteractionListener.itemSelected(/* Maybe Item Argument/)

class MainActivity: Activity(), OnFragmentInteractionListener {
    override fun itemSelected(/ Some Parameters*/ ) {
        startAct....
    }
}

I just want to call an activity by clicking on some items of my recycler view.
I really appreciate any help or suggestions you can provide.
Answer: Assume that you have a list of names(Strings) and you want to show them as a list. When one of these names is clicked you should show show clicked item(name) within another activity. You can implement it as following.
Your activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"
        tools:context=".MainActivity">

</androidx.recyclerview.widget.RecyclerView>

Adapter ItemRecyclerViewAdapter, subclass of RecyclerView.Adpater, which requires list of Strings as a constructor argument and which is able to accept OnAdapterInteractionListener(Edit: Placed inside the adpater) to interact with activity or fragment:
class ItemRecyclerViewAdapter(private val names: List<String>)
    : RecyclerView.Adapter<ItemRecyclerViewAdapter.MyViewHolder>() {

    private var nameClickListener: OnAdapterInteractionListener? = null

    fun setOnAdapterInteractionListener(listener: OnAdapterInteractionListener) {
        nameClickListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_name, parent, false)

        return MyViewHolder(view)
    }

    override fun getItemCount(): Int {
        return names.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.tvName.text = names[position]
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val tvName: TextView = itemView.findViewById(R.id.tvName)

        init {
            itemView.setOnClickListener {
                nameClickListener?.itemSelected(names[adapterPosition], adapterPosition)
            }
        }
    }

    interface OnAdapterInteractionListener {

        fun itemSelected(name: String, position: Int)
    }
}

And MainActivity class:
class MainActivity : AppCompatActivity() {

    private lateinit var mAdapter: ItemRecyclerViewAdapter
    private val names: ArrayList<String> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView.layoutManager = LinearLayoutManager(this)
        initNames()
        mAdapter = ItemRecyclerViewAdapter(names)
        mAdapter.setOnAdapterInteractionListener(object : ItemRecyclerViewAdapter.OnAdapterInteractionListener {
            override fun itemSelected(name: String, position: Int) {
                Intent(this@MainActivity, DetailActivity::class.java).also {
                    it.putExtra("name", name)
                    startActivity(it)
                }
            }
        })

        recyclerView.adapter = mAdapter
    }

    private fun initNames() {
        names.add("Name1")
        names.add("Name2")
        names.add("Name3")
    }
}

Next you should implement DetailActivity which handles StringExtra as shown bellow and sets it to TextView:
intent?.getStringExtra("name").also {
    detailText.text = it
}

Here detailText is a TextView.
Comment: It is better to put within `ItemRecyclerViewAdapter` bellow `MyViewHolder` inner class. I edited my answer @AndreAndriole
Comment: Hi, thx for the answer ! Where do I put the interface ? in another kotlin file ?
Comment: Im getting unresolved reference with adapter.setOnAdapterInteractionListener in the main activity. but I have it inside the adapter i dont know why unresolved
Comment: Strange that it works on companion object but there i cant "nameClickListener = listener"
Comment: Have you solved the issue, @AndreAndriole? If you have, please mark the answer as correct by clicking the check mark next to it, thank you!
Answer: You need to handle item click of an adapter. Refer to detailed answer here Passing data from one activity to interactor of another activity
Especially TaskItemListener usage in the sample.
Answer: It is pretty simple and straight forward. You have to create an interface to act as the listener and have to implement it in your activity. Then you should pass that implementation / reference to the adapter for accessing the interface method from adapter.
Sorry that it is in java. But you can follow the same method
Create and interface. You can create it inside the adapter / as a separate class (I am creating it inside my adapter)
public interface AdapterCallback{

        void onAdapterSelected(int pos);

    }

And inside the activity.
MyAdapter.AdapterCallback callback = new MyAdapter.AdapterCallback() {
        @Override
        public void onAdapterSelected(int pos) {
            Intent intent = new Intent(getApplicationContext(),
            SecondActivity.class);
            startActivityForResult(intent, 100);
        }
    };

Then pass this implementation to the adapter while creating it.
MyAdapter adapter = new MyAdapter(dataList, callback); //dataList is list variable name

You have to make changes in adapter constructor as well.
public MyAdapter(ArrayList<Student> data, AdapterCallback callback) {
            this.callback = callback;
            this.myList = data;
        }

Then inside onBindViewHolder, replace the start activity code with callback.onAdapterSelected
viewHolder.mBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onAdapterSelected(i);
                }

   });

Answer: None of the answers helped. I think they all have some java so that they dont work.
That said i solved the problem by :
in the adapter declaration
var ctx: Context? = null
```kotlin

in the listener inside adapter
```kotlin
(ctx as MainActivity).openProject()
```kotlin

in the listener inside adapter
```kotlin
fun openProject() {
        val intent = Intent(this, ProjectActivity::class.java)
        this.startActivity(intent)
    }
```kotlin

Well that solved my problem for now. If you know if doing an InterationListener insted is optimal or something please coment, thx.


Nginx/php-fpm timeouts

Question: I have a setup that consists of a load balancer, two web servers running nginx/php-fpm7.1 and a database server running mariadb.
For the past few months I have been struggling to work out the cause and resolve irregular timeouts and am finally asking on here for thoughts. Nothing had changed as far as I'm aware around the time of this occuring. Additionally, I have seen php-fpm fail totally and have to restart the service.
I'm seeing errors like the following and am receiving alerts throughout the day via xymon:
2018/07/11 14:27:23 [error] 13461#13461: *920760 upstream timed out (110: Connection timed out) while reading response header from upstream, client: *.*.*.*, server: www.something.com, request: "GET /something/something HTTP/1.1", upstream: "fastcgi://unix:/run/php-fpm/something.com.sock", host: "www.something.com"

There are about 5 sites hosted in the setup, with only one running through the load balancer, all others are pointed at webserver 1, as I receive alerts for all the sites I am looking only at webserver 1.
The general nginx conf all the sites use is as follows:
worker_processes        2;

user    nginx www-data;
pid     /run/nginx.pid;
worker_rlimit_nofile     100000;

events {
    worker_connections  1024;
    multi_accept        on;
    use                 epoll;
}

http {
    include             mime.types;
    default_type        application/octet-stream;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 200;
    client_max_body_size 16m;
    client_body_timeout 32;
    client_header_timeout 32;
    reset_timedout_connection   on;
    send_timeout   600;
    proxy_connect_timeout 600;
    proxy_send_timeout 600;
    proxy_read_timeout 600;

    fastcgi_buffers 8 128k;
    fastcgi_buffer_size 256k;

    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

Additionally, I have locations similar to this in each vhost
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/run/php-fpm/something.com.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 30s;
        include fastcgi_params;
    }

And each site has it's own fpm pool, all of which have the following changes:
pm = ondemand
pm.max_children = 12
pm.start_servers = 4
pm.min_spare_servers = 4
pm.max_spare_servers = 8
pm.max_requests = 15000

The main site that runs through the load balancer has the following fpm changes to it's pool
pm = dynamic
pm.max_children = 100
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 8
pm.max_requests = 15000

All the things I have attempted has resulted in no change, this includes updating all yum packages and rebooting. As it stands, there is no high load on these machines, although it can happen.
Any thoughts or help as to how to debug further would be very very useful!
Update
The slow log does report things like so:
[11-Jul-2018 14:53:12] WARNING: [pool something.com] child 53001, script '/var/www/something.com/index.php' (request: "GET /index.php?q=/404.html&") executing too slow (11.267915 sec), logging

Possibly more related to the maria server then?
Comment: Enable the php-fpm slow log and wait for a while until it happens again.
Comment: @MichaelHampton Sorry, I missed out that I have already done that. Will update the q
Answer: The thing that has most likely changed over time is the database size on the web server.
This and possibly inefficient SQL statements / DB structure might cause the fact that DB queries take too long time, and therefore the timeout occurs.
Comment: Yes, that's certainly increased... however they are wordpress sites so not much I can do re the structure. Going to look at that machine I think.
Comment: Well, then you need to look into caching solutions.
Comment: Yep, got a bunch of those sort of things in place in various nginx confs and other tools. However, seeing as there is little traffic though on the servers at the moment I don't feel that caching is going to solve that issue. Still, will look further into that.
Comment: nginx caching is only for static resources and has practically no effect on WP. Look at Memcached and appropriate WP plug-in for it.
Comment: Yep, its a custom setup with memcached/opcache where necessary along with various other bits and bobs... WP Plugs are ultra minimal and using a plugin to handle memcached is not something I would want to do at all for many reasons.

Nginx/php-fpm timeouts


Reading a Git repository, without Git

Question: I'm researching the idea of building a super-small (preferably PHP) web app, which will serve (among other things) as a minimal front-end to a git repository.
Any library/article for reading a git repository (".git" folder) without having to execute the "git" process? I'm looking for an API to manage a git repository. I'm only interested in basic functions, such as reading last commits (name of commiter, commit note, date), displaying and traversing branches...
Thanks,
ANaimi
Comment: Here's a good article on the subject: http://git-scm.com/book/en/Git-Internals-Git-Objects
Answer: Would this (git API documents) be of any help?
Here's a list of resources about extending php (i.e. to to provide wrappers around other library code):

extending php - an overview
writing php extension modules in C
PHP extension writing
writing extensions
Practical PHP Programming:Writing extensions
Extending PHP: examples
Writing a PHP Extension
Extension Writing Part I: Introduction to PHP and Zend
Zend API: Hacking the Core of PHP
PHP at the Core: A Hacker's Guide to the Zend Engine
Creating a PHP5 Extension with MS VC++ 2005
Writing a PHP Extension (C++)

Also, these would seem relevant, too:

git-php
git library?
Pure-Python Git Library
Git library?
libgit2 - a true git library & libgit2 source code at GitHub
php-git, a libgit2 binding
ActionScript3 git library
Comment: git API documents link is now broken :-(
Comment: And now it is no longer broken :-)
Answer: You may also want to check out the Cgit project since they've done something similar (except they build their own git library -- also to avoid running git directly).
There's JGit, a pure Java implementation, that may be useful to you.
Answer: Try also glip, a pure php implementation of git, which was extracted from eWiki.
Answer: I think that best start in such case  could be Interfaces Frontends And Tools page on Git Wiki.
You can find there link to eWiki (github) which supposedly uses native (in PHP) access to Git.
Comment: Yes actually that's what i'm doing right now. Looking at eWiki's code.

Reading a Git repository, without Git


Number of functions from $A$ to $A$

Question: We have the set $A=\{1,2,3,4,5\}$. what is the number of functions from $A$ to $A$?
I think the domain of the function should contain all the elements of $A$ but range of the function may have any elements of $A$ or not having them. so for each of the numbers from $1$ to $5$ we have two possibilities $(1)$ existing in the range of function. $(2)$ not existing in the range. so the number of functions from $A$ to $A$ is $2^5=32$. is my justification right?
Comment: Does this answer your question? [Let $X$ and $Y$ be finite sets. Then the set $Y^X$ is finite and $\#(Y^X) = (\#Y)^{\#X}$.](https://math.stackexchange.com/questions/4011693/let-x-and-y-be-finite-sets-then-the-set-yx-is-finite-and-yx-y)
Answer: No, you must take account of which element is mapping to which.
Each element of the domain can map to one of $5$ elements so the number of possible functions is $5^5$.

Number of functions from $A$ to $A$


Como faço herança de uma classe abstrata em C++?

Question: Em Java temos a possibilidade de criarmos classes abstratas, mais sem a possibilidade de instanciá-las, porém podemos criar e instanciar uma classe que herde os atributos e os métodos de uma progenitora abstrata. Em C++ isso é feito de uma forma diferente e eu gostaria de saber como se faz?
Até agora eu tentei fazer oque foi dito acima (ou quase), criar uma classe abstrata e herda seu atributos e métodos para outra classe que será instanciável. Segue o código:
Mother.h
#ifndef MOTHER_H_INCLUDED
#define MOTHER_H_INCLUDED

#include <string>

typedef std::string str;

class Mother{

    private:

        str test01;
        str test02;

        unsigned test03;

    public:

        virtual void setTest01(str teste01_)=0;
        virtual void setTest02(str teste02_)=0;

        virtual void setTest03(unsigned teste03_)=0;

    public:

        virtual str getTest01()=0;
        virtual str getTest02()=0;

        virtual unsigned getTest03()=0;

};

#endif // MOTHER_H_INCLUDED

//Red Hat

Mother.cpp
#include "Mother.h"

void Mother::setTest01(str test01_){

    test01=test01_;
}

void Mother::setTest02(str test02_){

    test02=test02_;
}

void Mother::setTest03(unsigned test03_){

    test03=test03_;
}

str Mother::getTest01(){

    return test01;
}

str Mother::getTest02(){

    return test02;
}

unsigned Mother::getTest03(){

    return test03;
}

Daughter.h
#ifndef DAUGHTER_H_INCLUDED
#define DAUGHTER_H_INCLUDED

#include "Mother.h"

class Daughter: virtual public Mother{

};

#endif // DAUGHTER_H_INCLUDED

main.cpp
#include "Mother.h"
#include "Daughter.h"

int main(void){

    Daughter tst;

    return 0;
}

Quando compilo o programa com o GNU g++:

error: cannot declare variable 'tst' to be of abstract type 'Daughter'
  Daughter.h|6|note: because the following virtual functions are pure within 'Daughter':|

...entre outros erros e avisos
Comment: A ideia de ter métodos abstratos na classe base é para que eles não tenham implementação nessa classe base e apenas nas classes derivadas. Já para não falar que é bem incomum um getter ou setter ser abstrato.
Comment: @Isac Vivendo e aprendendo! não sabia desse negocio de getter e setter ser incomum como abstratos. Obrigado pelo seu comentário.
Comment: @Isac "A ideia de ter métodos abstratos na classe base é para que eles não tenham implementação nessa classe base e apenas nas classes derivadas." - Então no caso estou incorreto ao implementar minha classe base abstrata em um arquivo .cpp?
Comment: Seria incorreto, a ideia é não implementar na base. Se vai implementar na classe base então não os coloque abstratos, retirando o `=0` em cada um deles.
Comment: @Isac Blz! Então eu vou implementar na Daughter.h? Mais como faço isso?
Comment: Não no seu caso faria sentido deixar a implementação na `Mother.h` mas sem ser abstrata, porque dificilmente iria querer dar outra implementação diferente na classe derivada. Mas é um pouco de difícil perceber o que pretende fazer num exemplo tão exotérico.
Comment: @Isac Cara...mais o negocio aqui não é se faz sentido e sim eu saber como eu vou fazer a herança de uma classe abstrata, não é atoa que o nome das variáveis tem "test" pra todo lado.
Answer: Discordo do comentário que diz que getters/setters abstratos são incomuns. Na verdade em C++ o mecanismo de getters/setters são incomuns, mas onde eles são usados é comum o uso, se fizer sentido, a classe ser realmente abstrata, o que muitas vezes não faz, aí nem seria caso incomum, seria errado.
Concordo totalmente que um exemplo de classe com nomes abstratos e sem uma definição clara do que o objeto é não dá para modelar nada direito. O que pode ser certo para um caso pode ser muito errado para outro. Se fizer algo que não faz sentido então está errado e não deve fazer.
Tanto o Isac quanto eu e vários outros usuários aqui temos o compromisso de ensinar certo, podemos errar, mas tentamos acertar o tempo todo. Seria irresponsável de nossa parte aceitar algo errado tendo conhecimento que está. Então tem algumas soluções dependendo do que é o objeto.
Classe abstrata
A classe não é abstrata ou pelo menos parte dela não é abstrata (sim, é possível ter uma parte abstrata e outra não, claro que a classe será considerada abstrata e não instalável com apenas um método abstrato, mas o resto dela não precisa ser abstrato:
class Mother {
    string test01;
    int test03;
    public:
        virtual string getTest01();
        virtual void setTest01(string teste01);
        virtual int getTest03();
        virtual void setTest03(int teste03);
};

string Mother::getTest01() { return test01; }
void Mother::setTest01(string test01) { this.test01 = test01; }
int Mother::getTest03() { return test03; }
void Mother::setTest03(int test03) { this.test03 = test03; }

Daughter.h
class Daughter: virtual public Mother {}; //só faz sentido se fizer mais alguma coisa

Interface
Se quer que os métodos sejam abstratos não faz sentido ter atributos, então podemos transformar esta classe um uma interface:
class Mother {
    public:
        virtual string getTest01() = 0;
        virtual void setTest01(string teste01) = 0;
        virtual int getTest03() = 0;
        virtual void setTest03(int teste03) = 0;
};

Daughter.h
class Daughter: virtual public Mother {}; //não muito, mas aqui até faz sentido

string Daughter::getTest01() { return test01; }
void Daughter::setTest01(string test01) { this.test01 = test01; }
int Daughter::getTest03() { return test03; }
void Daughter::setTest03(int test03) { this.test03 = test03; }

Coloquei no GitHub para referência futura.
Simplifiquei porque se é um exemplo abstrato não tem porque colocar mais que o mínimo necessário. Eu poderia ter tirado o Teste03, não o fiz para mostrar que uso do int (quase sempre o uso do unsigned é um erro e quando não é costuma-se usar unsigned int (programar para você entender entender é fácil, para todos entenderem é mais difícil). Usei-o também para mostrar que costuma-se agrupar os método pelo que eles são e não pelo que eles fazem. Tem que deixar próximo o que está relacionado.
E ainda usei string porque aquele typedef só serve para causar problemas de legibilidade e comer algum erro sem querer.
Claro que eu tirei partes do código que não são necessários para o entendimento do problema já que é um exemplo abstrato demais.
Não fiz um exemplo de classe abstrata (no lugar de uma interface) porque o exemplo é abstrato demais, mas seria possível ter atributos em casos onde faça sentido (não este).
Fiz outras melhorias cosméticas, mas importantes.
Comment: Está demonstrado na resposta.
Comment: Qual a diferença entre colocar a função somente como virtual e colocar como virtual porém com um "=0" no final?
Comment: `virtual` deixa a função ser sobrescrita, `= 0` faz ela não ter implementação.
Comment: Ok, nesse caso não fazeria sentido colocar '=0' no final de uma função virtual caso queira implentar essa função em outra classe???
Comment: Não entendi a dúvida.
Comment: Desculpa! Confundi as bolas. O'que eu queria dizer é se por a caso quando colocamos '=0' no final de uma função estamos dizendo para ela ser um metódo final?
Comment: Não, é exatamente o oposto disto, algo que não tem uma implementação jamais poderá ser `final`, ainda que isto não exista em C++.
Comment: Em C++ uma classe abstrata pode conter logica(código)?


Extracting a subsequence from an array

Question: I'm trying to solve an algorithm for extracting a subsequence from an array. It should display the longest subsequence of prime numbers. I have written the whole algorithm but I still get an infinite cycle and I can't figure out where and why. I'm incrementing both indices and modifying the first index at the end, but it is still not working. Thanks a lot !!!
P.S: citire reads the array, prim detects if a number is prime or composed, afisare displays the subsequence and detSecv determines the longest subsequence.
#include <iostream>
#include <math.h>

using namespace std;

void citireSecv(int &n,int x[50])
{
    cout<<"Da n: ";
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cout<<"Da un nr: ";
        cin>>x[i];
    }
}

int prim(int n)
{
    int d=2;
    while(d<=sqrt(n) && n%d!=0)
    {
        if(d==2)
            d=3;
        else
            d=d+2;
    }
    if(d>sqrt(n)) return 1;
    else          return 0;
}

void afisare(int n,int x[50],int st,int f)
{
    for(int i=st;i<=f;i++)
        cout<<x[i]<<" ";
}

void detSecv(int n,int x[100],int &st,int &f)
{
    st=1; f=0;
    int i=1,j;
    while(i<=n-1)
    {
        while(i<=n-1)
        {
            if(prim(x[i])==0 && prim(x[i+1])==0) i++;
        }
        j=i+1;
        while(j<=n-1)
            if(prim(x[j])==0 && prim(x[j+1])==0) j++;
        if((j-i) > (f-st))
        {
            st=i;
            f=j;
        }
        i=j+1;
    }

}

int main()
{
    int n,x[100],st,f;
    citireSecv(n,x);
    detSecv(n,x,st,f);
    afisare(n,x,st,f);
    return 0;
}

Input data:
n=2
First number is: 5
Second number is: 7

Comment: Fyi, ,this is what debuggers were made for. Also, include your input data that reproduces your infinite loop as part of the question in s separate list.
Comment: I updated my question for input data. Regarding debugger, I'm really used to it, because I usualy use Eclipse for Android Developing. I'm very new to this Codeblocks and C++. Thanks !
Answer: Probably just one of many issues with that code:
    while(i<=n-1)
    {
        if(prim(x[i])==0 && prim(x[i+1])==0) i++;
    }
    j=i+1;
    while(j<=n-1)
        if(prim(x[j])==0 && prim(x[j+1])==0) j++;

There are two potential infinite loops here. If the conditions in the while don't return true on the first iteration, i (or j) will never get incremented, and you will have your infinite loop. You should almost always increment such variables outside of any conditions.
Comment: @Ezek - use two variables: one for iterating, the other for keeping track of the longest length. Or change your while condition to iterate while your primality condition is true.
Comment: I will give it a try even if I didn't really get the whole idea. Thanks a lot !
Answer: With a slight change in your code, you make it work, and one thing, you don't need to start array with index 1. you can always start with index zero.
for(int i=1;i<=n;i++)
{
    cout<<"Da un nr: ";
    cin>>x[i];
}

try to check for a case when no prime subsequence is found, while printing.
void detSecv(int n, int *x, int &start, int &end)
{
    start = -1;
    end = -1;
    int i=0,j;
    while(i < n) {
        if(prim(x[i])) {
            j = i + 1;
            while(j < n)
                if(prim(x[j])) j++;
                else break;
        } else {
            i++;
            continue;
        }
        if((j-i) > (end - start)) {
            start = i;
            end = j-1;
        }
        i=j+1;
    }
}

Answer: This is a better way to verify if a number is prime or not
bool IsPrime(int number) {
int primeStep = 2;
double stepLimit = sqrt(number);
while(primeStep <= stepLimit)
{
    if(number % primeStep == 0)
        return false;
    primeStep += 1;
}
return true;
}

And nou you can apply that function for each number in your array, and if it's prime , you add it in a new array like this:
void detSecv(int numberOfItems,int *arrayOfNumbers)
{
   int arrayOfPrimeNumbers[50] = {};
   int index = 0;

 for(int i = 0; i < numberOfItems; i++)
 {
    if(IsPrime(arrayOfNumbers[i])){
        arrayOfPrimeNumbers[index] = arrayOfNumbers[i];
            index += 1;
    }
}

int secondIndex = 0;
while(arrayOfPrimeNumbers[secondIndex] != 0)
{
    cout << arrayOfPrimeNumbers[secondIndex] << " ";
    secondIndex += 1;
}
}

Extracting a subsequence from an array


Equations of triangle sides through medians

Question: This has been bothering me for a while.
Given a vertex $A(2;-4)$ and the line equations of two medians ($2x-3y-2=0$ and $5x+3y-12=0$), find the line equations on which the triangle sides are.
I've tried to approach this several ways, e.g. finding the reflections of point A about the medians, but the answers always seem to be off the mark.
I'd appreciate some guidance!
edit:
So I don't seem to be able to comment on other posts (or this post for that matter) so I'll just reply to hhsaffar's answer here:
So I did find the intersection point of the medians previously $\left(2, \frac{2}{3}\right)$ and the equation for the third median ($x=2$). I also have the coordinate (referring to hhsaffar's triangle here) $F(2, 3)$. However I have trouble figuring out the next step.
Answer: You need coordinates of $B$ and $C$, so you have four unknowns. So you need four equations. You have equations of $CD$ and $BE$, this gives you two equations. You also know the coordinates of $G$. This gives you another equation. Now for the last equation note that $AG$=$2GF$ and $BF=FC$.
Answer: Refer to the figure below.

Let A be (2, -4) and B be (p, q).
L(1) : 2x-3y-2=0
L(2): 5x+3y-12=0
Testing showed that A is not on either L(1) or L(2).
Note: the next 6 lines can be skipped.
Solving the above, we have G, the centroid is at (2. 2/3).
This means A and G are on the same vertical line x = 2.
AG = (2/3) + 4 = 14/3
Let A(h) and C(h) be the feet of the medians through A onto BC and C onto AB respectively.
By the properties of centroid, GA(h) = 0.5*AG = 7/3
A(h) is then at (2, 3).
The midpoint of AB = C(h) = ([p + 2]/2, [q – 4]/2).
It lies on L(2). Therefore, 5[[p + 2]/2] + 3[[q – 4]/2] -12 = 0………(1)
B(p, q) lies on L(1). Therefore, 2(p) – 3(q) – 2 = 0……………………..(2)
Solving (1), and (2), we have B = (4,2).
The co-ordinates of C can be similarly obtained.
The required equations can be obtained by applying two-point form.
Comment: You are welcome.


What is the name of this drums "disco" rhythm/technique?

Question: I can hear this drums beat in several songs, but could never find a tutorial about it because I don't know what it's called.
Genesis - Abacab

 (listen to the drums at 3:08)
Another example:
WALK THE MOON - Shut Up and Dance

 (listen to the drums at 1:48)
Comment: @ToddWilcox, isn't this a question about a drum technique in general? Off-beat open hi-hats are ubiquitous in funk and rock. I don't think this is a question about a specific element found in one particular song. Two different examples are cited, and many more could be found.
Comment: Don't see what you are asking about.
Comment: Hi Tim, I believe you listened to the songs I posted. If I wanted to learn that "drum rhythm" with the hi-hat opening and closing, what should I search for? Is there a name for that drum beat?
Comment: Identifying elements in songs like that is off topic here, but that is one of the most popular drum beats in all of music. Because of that, you will find that beat in this list of 7 beats all drummers should know: https://youtu.be/N3gTWZU9TtI?t=12m48s
Comment: @jdjazz Well you make a good point. I guess to me it could go either way.
Answer: The hi-hat technique is specifically referred to as "hi-hat lifts," "open hi-hats," and "opening/closing hi-hats." In both songs, the high-hat lifts are occurring on offbeats, which is very common in a disco beat like these.
Hi-hat technique
The technique involves playing the hi-hat on the downbeats and upbeats. On the upbeat, you lift the hi-hat with your left foot. At the same time as you lift the hi-hat, strike it with your stick. On the downbeat, you depress the pedal to close the hi-hat. To avoid a double hit on the downbeat, you strike the hi-hat with your stick at the same time as your foot depresses the hi-hat pedal. In most cases, you don't want to open the hi-hat fully and just want to open it slightly. The more open your hi-hat, the more the sound will ring out. But for a lot of scenarios, you're making pretty subtle foot movements.
Disco beat
The hi-hat technique creates a nice backbeat, which you can accentuate by adding the snare on beat 2. To get a complete disco beat, you can add the bass drum on all four beats (1, 2, 3, 4). The total result is something like this:

And here's a video of the hi-hat technique alone:
Comment: The beat as a whole is a *disco* beat. It's not just the open high hat pattern. It's also the kick on every beat including when the snare is played.
Comment: Link to Disco beat example video is dead.


Como definir os requisitos básicos para rodar aplicação Java desktop?

Question: Como faço para identificar os requisitos mínimos (memória RAM, processador, etc.) para minha aplicação rodar?
Não tenho diversos computadores para testar com várias situações. O computador que utilizo para desenvolvimento possui especificações um pouco acima dos computadores "comuns", nada tãão acima, mas acredito q o sistema não necessite de tudo isso. Sei que depende das funcionalidades, frameworks, banco de dados, et., mas há algum software ou uma dica para que eu possa identificar um requisito mínimo para que o sistema rode sem problemas?
Comment: No diretório java/jdk1.X.X_XX/bin tem dois utilitários jconsole.exe e o jvisualvm.exe (java8). Coloque sua aplicação para rodar e monitore o uso da memória, uso da CPU, etc. Acho que pode servir de base para determinar os requisitos da aplicação.
Answer: Note que existem duas correntes para especificar o mínimo. Uma delas é usar o mínimo mesmo, ainda que isso quase inviabilize o bom uso da aplicação. Outra é um mínimo que garanta o bom uso, em geral nesse caso costuma-se exagerar propositalmente.
O único jeito certo mesmo é testar em vários computadores. Em alguns casos é possível limitar artificialmente algum recurso de um computador para simular algo inferior, mas não sei se compensa.
Na verdade, na prática, é raro fazer isso, principalmente em software que poucas pessoas usarão. O que se faz é estimar o uso. Muitas vezes é só reproduzir o que o Java já exige, talvez com alguma folga.
Precisa ver também qual é o sistema operacional (incluindo versão) precisa usar e outras dependências, entre elas banco de dados. Não é só processador e memória que existe requisito.
Desktop
O Java roda em qualquer processador minimamente moderno. Você pode adotar algum limite mínimo arbitrário. Tipo: processador Intel compatível com pelo menos 2 (talvez nem isso) núcleos e/ou 2.0Ghz.
Claro que pode usar alguma biblioteca que exija algum recurso específico de algum processador. Tem que ver isso com essa biblioteca e adotar essa necessidade. Ou seja, tem que conhecer o que está usando para especificar o que precisa. Os testes não são necessários de fato. A especificação de outros serve de base para a sua.
Se existir algum motivo para exigir mais, coloque, isso deve ficar óbvio no uso da aplicação. Lembrando que o mínimo não é necessariamente o recomendável para melhor uso.
Uma coisa comum é exigir que seja 64 bits em alguns casos. O que fica óbvio se for exigir mais de 2GB de memória.
Em tese a maioria das aplicações Java precisam de alguns megabytes de memória. Então nada impede de dizer que o mínimo é 1GB, já que o sistema operacional deve exigir isso (Linux sem GUI pode exigir menos, mobile também). Claro que o ideal é dar uma folga, então costuma-se colocar 2GB. Se quiser dar uma experiência mais tranquila pode exigir 4GB.
Se a aplicação é devoradora de memória pode ser útil exigir mais, existem casos extremos que podem exigir 32, 64 ou mais gigabytes. Se você não souber que a aplicação devora memória desse jeito, o menor dos seus problemas é especificar o requisito, você provavelmente não tem ideia do que está fazendo e isso é muito perigoso.
Há quem fale em memória só para a aplicação. Nesse caso pode tentar rodar sua aplicação por um longo período e ver na ferramenta que monitora a memória no sistema operacional o pico que deu. Não é preciso, mas dá uma ideia, coloque um pouco de folga e divulgue isso. Também pode rodar um pouquinho e ver quanto deu não fazendo quase nada. Dá um mínimo baixo, mas é enganoso (tem gente que faz isso).
Idealmente seria útil usar uma ferramenta de profiling, mas sem saber o que fazer com ela não adianta muito. Uma forma de monitorar é como o que o Edson F. Santos postou no comentário acima.
Memória nunca é demais até que o bolso reclame forte ou seja obviamente exagerado. Hoje tem desktop rodando com 32GB ou mais, é exagerado para alguns casos, mas não para todos. Hoje 8GB deveria ser o mínimo de qualquer desktop.
Servidor
Aqui a coisa fica mais complicada. Nem vou falar se o servidor compartilha banco de dados.
Em geral um servidor não pode ser pouca coisa, se ele for muito inferior a necessidade, vai rodar, então pode até especificar algo parecido com um desktop, mas a experiência será bem ruim.
Fora você ter experiência com muitos casos, o que não parece ser a situação, só medindo mesmo, ainda que a medição não seja perfeita, dá uma base. É rodar dentro da carga esperada e ver como se comporta, ver se o processador está batendo em 100% por muito tempo, se fica fazendo swap em "disco", tudo isso é um sinal de alerta.
É comum precisar ter vários núcleos no servidor para responder bem, mas depende do tipo de carga. Mínimo mesmo, qualquer coisa serve. E tem aplicação que ter vários núcleos não vai ajudar nada, mas aí talvez seja problema da aplicação.
Servidor tende a precisar mais de memória, mas também pode ser que ela seja mais necessária para o banco de dados.
Se a aplicação faz uso intensivo de cache, vai rodar com um mínimo básico, mas será muito melhor se tiver bastante memória para manter mais cache.
Se quiser uma informação mais precisa, não tem jeito, terá que ficar bom em profilling.
Dispositivos móveis e uso especializado
Aí você não deve ter muito controle. O mais comum é fazer a aplicação caber no que tem disponível no grosso do mercado (e é pouco ainda no Brasil, infelizmente).
Conclusão
Lembre-se que a aplicação muda e o mínimo pode mudar. Uma simples adição de algo que precise carregar algo grande na memória pode mudar tudo.
Coloquei no GitHub para referência futura.
Comment: Olá, desculpe a demora, e muito obrigada pela resposta, ajudou bastante!


TypeError: instance.render is not a function in React

Question: Hello good evening devs my problem is the following react when trying to load my application gives me the following error
Error React
import React from 'react';
import { Card, CardImg, CardText, CardBody, CardTitle } from 'reactstrap';

class DishDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
  }

  renderDish(dish) {
    if(dish != null) {
      return (
        <Card>
            <CardImg top src={dish.image} alt={dish.name} />
            <CardBody>
            <CardTitle>{dish.name}</CardTitle>
            <CardText>{dish.description}</CardText>
            </CardBody>
        </Card>
      );
    }

    else {
      return (

      );
    }
  }

  renderComments(dish) {
    if (dish.comments != null) {
      const comments = this.props.dish.comments.map(review => (

              {comments}

{review.comment}

{review.author}

{review.date}

      ));
    }
    else {
      return (

      );
    }

    return (

          {this.renderDish(this.props.selectedDish)}

comments

    )
  }
}

export default DishDetail;

I have made several changes to the code I am using the ES6 syntax, I would appreciate your help as I am trying to render from one component to another
Answer: The problem is in react class component you need to use render function to return the jsx you want to render if the last return is something you want to render then do it like this:
    import React from 'react';
    import { Card, CardImg, CardText, CardBody, CardTitle } from 'reactstrap';

    class DishDetail extends React.Component {
      constructor(props) {
        super(props);
        this.state = {

        }
      }

      renderDish(dish) {
        if(dish != null) {
          return (
            <Card>
                <CardImg top src={dish.image} alt={dish.name} />
                <CardBody>
                <CardTitle>{dish.name}</CardTitle>
                <CardText>{dish.description}</CardText>
                </CardBody>
            </Card>
          );
        }

        else {
          return (

          );
        }
      }

      renderComments(dish) {
        if (dish.comments != null) {
          const comments = this.props.dish.comments.map(review => (

                  {comments}

{review.comment}

{review.author}

{review.date}

          ));
        }
        else {
          return (

          );
        }

      }
     render(){
      return (

              {this.renderDish(this.props.selectedDish)}

comments

{this.renderComments(this.props.selectedDish)}

        )}
    }

    export default DishDetail;

Comment: Thanks you so much bro @aravind_reddy your solution worked beautifully!!
Comment: I need to render the comments in the view but so far I haven't been able to do it. @aravind_reddy
Comment: @wildsrincon i have updated the answer you need to call the `renderComments` from render return to be able to see on the screem


Diminished chord with one raised note

Question: I have no formal training in music theory, so my question might be phrased a bit clumsily.
There is a kind of jazzy chord progression I enjoy very much, the one which, from the top of my head, I think is in the refrain of Frankie Valli's "Can't get my Eyes off you". (Correct me of I'm wrong). It's like a ii-V-I, but starting further up.
If played in C, I start out with an Fmaj7 major chord, and move just move down the circle of fifths, in a easy fingered pattern that I have a feeling a lot of you will know what I'm talking about.
After I reach Cmaj7, I lead back to the first chord in the progression with an A7 chord. (If anyone can tell me a formal name for this kind of chord progression, it would be much appreciated)
These are the 8 chords exactly:
FACE
FABD
EGBD
EGAC
DFAC
DFGB
CEGB
AC#EG
So, except for wondering if this progression is a common thing that has a name, I'm wondering about the second chord here, FABD. What exactly is this chord? It seems to be a diminished chord with one of its notes raised a semitone (G# to A). Am I even supposed to play this chord like this? (I mean, I think it sounds good, but have I just trained my ear to like it?) Is this type of progression usually played with a regular dim chord at this position?
I hope I have stated my inquiry clearly, and I appreciate any information anyone might have to help me!
Answer:
I'm wondering about the second chord here, FABD. What exactly is this chord?

In root inversion, the chord would be written BDFA. It consists of root, m3, d5, m7. Since the 5th is diminished but the 7th isn't (otherwise it would be an A♭, as you note), this chord is called a B half-diminished seventh chord. It is notated as Bm7♭5 ("B minor-7 flat-5") or as Bø7.
For comparison:

B diminished = B-D-F
B diminished seventh = B-D-F-A♭
B half-diminshed seventh = B-D-F-A

wondering if this progression is a common thing that has a name

The full progression you have written is:
FM7 - Bm7♭5 - Em7 - Am7 - Dm7 - G7 - CM7 - A7
As you point out, with the exception of the last A chord, the rest of the sequence just follows the circle of fifths. Naturally, it is called a Circle Progression, and it is pretty common in both classical and jazz. I'm not sure there's really a specific name for adding the final A7 chord, though. I'd almost consider it more of a passing chord. It looks like it wants to lead to D minor.
EDIT: The final A7 is an example of a turnaround, which is a way to add harmonic movement to what would otherwise be a single, prolonged chord. There are many types of turnarounds, and they don't necessarily have individual names.
Comment: Well sure, but it would be a complete circle even without the A7, since CM7 leads back into FM7.
Comment: Dm = DFA. Dm7 =DFAC.Dm9 =DFACE. Pretty well back to the first chord- FACE. Almost a completed circle ?
Comment: Those notes, D F A B also constitute the chord known as Dm6. Every half-diminished seventh chord is an inversion of another m6, a m3 away.
Answer: Good info above, but I think the progression for the jazzy part of the tune is simply this (in E):  ('-' == minor, sorry for the jazz shorthand)
F#-7  B9   E6   C#-7
F#-7  B9   E6   C#7(#9)
Or if you prefer, back in C:
D-7   G9   C6   A-7
D-7   G9   C6   A7(#9)
This is just a ii-V-I based progression, very common in jazz.  The fourth chord prepares to go back to the ii (somewhat weakly), as does the eighth chord (with more strength!).

Diminished chord with one raised note


linux redhat + swapoff is stuck not return prompt

Question: I do the following steps in order to increase the swap size
but when I start with swapoff /dev/mapper/rootvg-swap , then its stuck for along time and not return the prompt
why we can do to solve this
 swapoff /dev/mapper/rootvg-swap
 lvresize -L +5g  /dev/mapper/rootvg-swap
 mkswap /dev/mapper/rootvg-swap
 swapon /dev/mapper/rootvg-swap

 vmstat 1
 procs -----------memory---------- ---swap-- -----io---- --system-- ----- cpu------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0 2027848 127788  28804 18490972  105   38   180   211   25   59 17  6 64 13  0
 1  0 2027848 126944  28812 18490972    0    0     0   124 1073 1491 16  1  82  1  0
 0  0 2027848 126076  28828 18490956    0    0     0   104  727 1236  6  0    94  0  0
 0  0 2027848 126076  28828 18491008    0    0     0     0  452  979  2  0 98  0  0
 1  0 2027696 130960  28828 18486500  480    0   480    92  985 1415 21  4 69  5  0
 0  0 2027696 130984  28844 18486572    0    0     0    43  421  984  1  0 98  1  0

Comment: What would expect? if you using this laaarge amount of swap it need some time to free it. run `vmstat 1` and watch the decreasing swap.
Comment: How long time? Btw. using 10+GB as swap isn't a good choice.
Comment: more then 2-3 min , I stop it with CNTR-C
Comment: see my update ( the problem is swapoff /dev/mapper/rootvg-swap take more then 3 min and not sure if it will return prompt even after 10 min )
Comment: vmstat clearly says that you don't have enough free memory for copying the whole swap.
Comment: so what is the workaround for this , how to solve this ?
Comment: do I need first to add memory ( like 2G ) and then to perfrm swao off ?
Answer: I experienced this problem recently on a Centos 7 VM. I stopped and started swapoff several times because I was impatient and thought "nothing was happening".
On the last effort I tried running swapon --show on a separate terminal a few minutes apart and saw that the amount of swap being used was reducing, albeit at a snail's pace - i.e. 1.5MB/s, so it took about an hour and a quarter to finish as about 6.5GB were in swap - although there was plenty of main memory available. Eventually it finished successfully.
Comment: Thanks a lot! I just experienced a very similar behavior of a Centos 7 server where 2GB of swap was being freed for ~ 1 hour. I would not expect this if I hadn't read your answer.
Answer: The swapoff command needs to flush all of the swapped memory from the swap file (/dev/mapper/rootvg-swap) back to main memory (or perhaps somewhere else) before it can disable the swap file. This can take time to complete and you may not have sufficient free memory.
You can increase the amount of free swap space that you have by adding more swap files

create a swap file/LV depending on what you have available
use mkswap to configure it
use swapon to enable it

The swapon man page contains more information about multiple swap files that may be helpful in particualar look at priorites.
The safest way to solve your problem is likely to reboot to single user mode and carry out the porcess you outline when the system is not under memory pressure.
The best solution is to size your system appropriately for its workload and to add more memory.


Placement of vocal soloists with orchestra

Question: A recent trip to a major symphony orchestra to see Beethoven's Missa solemnis led me to wonder. In every performance of this work I've seen, the soloists have been placed at the back of the stage, just in front of, or sometimes as part  of, the chorus. By comparison, in many other classical works, such as the Mozart Requiem, Beethoven's Mass in C, and the Verdi Requiem, I've always seen the soloists at the front of the stage, in their "usual" positions.
Are there specific reasons why, in certain works, soloists will be at the back of the stage—particularly in "older" music where the composer may not have thought it necessary to indicate a stage position other than at the front of the platform, by the conductor?
Answer: Before I answer your question, this is the BBC orchestra performing the Missa Solemnis with soloists in front.
To answer your question, I will ask another question: Why are there dozens of different wind ensemble setups?  Why are there different setups for orchestras and choirs?  The answer to this question is that each setup creates a different sound and allows ensemble members to hear the one another different.
Different ensemble setups are also created for different group skill levels.  You wouldn't put a middle-school choir in a mixed quartet setup; nor would you have them sing 4-part music for that matter.
Soloists are often put at the front of the stage for clarity of text, projection, and balance - that's why orchestras play in pits for opera.  If the soloists are put elsewhere, it could be for dramatic effect or to take better advantage of the space.  One great example of this is Benjamin Britten's War Requiem where in the premiere at Coventry Cathedral the two male soloists were placed on one side with the full orchestra and the female soloist was placed with the children's choir and chamber orchestra on the other side.
If space is cramped, there may not be anywhere for the soloists to go except squished by the orchestra unfortunately.  If space is not cramped and there is no viable reason for them to be back there, then it is an oversight of the conductor and director as they will be that much harder to understand.
With respect to the Missa Solemnis specifically, Beethoven was well into beginning to lose his hearing, so I doubt it mattered much to him anyway - especially because he never actually heard the entire piece premiered in his lifetime.
I am not aware of any specific historical practice with respect to placement of soloists in front of the choir.
Hope that helps.
Comment: Thanks for the answer. However, a few points: (1) My middle-school choir did four-part music--quite often, in fact! (2) I think you have the soloist disposition in the _War Requiem_ backwards (remembering the photos I've seen). (3) I've noticed this phenomenon with certain works, and not others, in the same venue with the same forces. For instance, I've seen the BSO do the Verdi and Mozart _Requiems_ and place the soloists out front, but _not_ for the _Missa Solemnis_!
Comment: To respond to your comment: 1.) That's impressive! I'm envious of your middle school program. 2.) Yes, you are correct!  Please excuse me.  I wrote a research paper on it and some of the information has gotten a little garbled over time. 3.) The only other thing I can think of would be that it was an old performance practice of simply having vocalists near vocalists - take Haydn for example: [link]https://www.youtube.com/watch?v=S03cwGuw43s
Comment: Verdi did live much longer beyond Beethoven's life, but he could have been just using an old technique - or Beethoven could have been trying to break the convention by having the soloists be away from the chorus.  After all, the 9th symphony doesn't use the choir or soloists until the last movement, so they have to sit there like ducks the entire time.
Answer: I always got the feeling this was historical - that having the depth of stage to allow for separation of soloist and choir was relatively uncommon, and certainly less common than it is now with many venues having large stage areas.
It is also sometimes the case that the soloists only step out of the body of the choir for particular pieces, and that seems to be a couple of metres in front of the choir.
Heading right out to the front of the stage has a nice dramatic emphasis, but I'm wondering whether it has come about just as a result of the increased area available, and the increasing fame of soloists over the years.
Comment: Thanks for the answer, but I think this misses the mark somewhat. I was curious about placement of soloists when there's an orchestra involved. The "couple of metros" argument doesn't normally apply in those circumstances, because the typical stage is packed full of choristers and instrumentalists in such circumstances. My question is then: why do they place soloists with the chorus for some orchestral works, but at the front of the platform for others? Is it a historical tradition for those works, or is something else at work?
Comment: My final paragraph covers my thoughts on that.


How to install a NodeJS package from a github repo

Question: I'm trying to install a package from a github repo but I get the following message:
npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/z0019rb/.nvm/versions/node/v4.4.7/bin/node" "/Users/z0019rb/.nvm/versions/node/v4.4.7/bin/npm" "install"
npm ERR! node v4.4.7
npm ERR! npm  v2.15.8
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/target-digital-design-tokens
npm ERR! 404
npm ERR! 404 'target-digital-design-tokens' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 It was specified as a dependency of 'target-base-pattern-library'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/z0019rb/dev/design-systems/designsystems-site/npm-debug.log

And this is what my package.json looks like:
"target-digital-design-tokens": "git+ssh://firstname.lastname@example.com:design-systems/design-tokens.git"

Not sure what I'm doing wrong. The repo which I'm trying to install has a package.json. Thanks!
Comment: what command are you using to install? The package.json entry looks fine.
Comment: Did you try it using https only? eg. npm install https://git.target.com/design-systems/design-tokens.git
I think it's an issue with the source, which cannot be accessed
Comment: Wild guess: try a `/` instead of a `:` after `git.target.com`?
Comment: I'm doing `npm install` to install. I tried using https but it doesn't work. I've tried all these options.
Comment: The strangest thing is even after removing this package from package.json, npm tries to install it but it has no reference in my package.json file. How can it be possible?
Answer: try this instead                           :
"git+https://target.com/design-systems/design-tokens"

and don't forget to set git repo in your package.json like so :
"repository": {
    "type": "git",
     "url": "firstname.lastname@example.com:design-systems/design-tokens.git"
 },

If the git server is behind a proxy don't forget to set env http_proxy before npm install something like this :
npm config set proxy "http://domain......@myproxy:8080"
npm config set https-proxy "http://domain......@myproxy:8080"

Comment: That doesn't' seem to work. The interesting thing is it used to work before and I didn't change anything.


Ubuntu 10.04 SNMP No Change In ifInOctets / ifOutOctets

Question: I have succesfully set up cacti on 3 different Ubuntu machines here to monitor bandwidth usage.  Upon trying to set it up on a remote machine, the bandwidth counter does not change.
#snmpwalk -v 2c -c public 127.0.0.1 .184.108.40.206.188.8.131.52.1.10; sleep 10; snmpwalk -v 2c -c public 127.0.0.1 .220.127.116.11.220.127.116.11.1.10
result
IF-MIB::ifInOctets.1 = Counter32: 221594
IF-MIB::ifInOctets.2 = Counter32: 0
IF-MIB::ifInOctets.3 = Counter32: 6670994
IF-MIB::ifInOctets.4 = Counter32: 0
IF-MIB::ifInOctets.5 = Counter32: 0
IF-MIB::ifInOctets.6 = Counter32: 0
IF-MIB::ifInOctets.1 = Counter32: 221594
IF-MIB::ifInOctets.2 = Counter32: 0
IF-MIB::ifInOctets.3 = Counter32: 6670994
IF-MIB::ifInOctets.4 = Counter32: 0
IF-MIB::ifInOctets.5 = Counter32: 0
IF-MIB::ifInOctets.6 = Counter32: 0

Given a little time - 15 minutes or so, it does change.  I've purged and reinstalled identically to the other machines with no success.  I've also tried the 64 bit counters with no luck either.  Utilizing v1 & v3 also produces the same result.
Using ifconfig
Gives:
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:320474 errors:0 dropped:29 overruns:0 frame:0
TX packets:433453 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:22979993 (22.9 MB)  TX bytes:407158360 (407.1 MB)
Interrupt:44

a few seconds later:
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:323653 errors:0 dropped:29 overruns:0 frame:0
TX packets:436633 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:23186461 (23.1 MB)  TX bytes:407336648 (407.3 MB)
Interrupt:44

Data is being moved, just not registering with snmp.
snmpd.conf:
rocommunity  public
syslocation  "Over Here"
syscontact  email@example.com

Answer: I have just had the same problem myself, after searching around a lot and thinking that the problem was similar to this:
http://www.fineconnection.com/How_to_set_the_net-snmp_agent_update_or_counter_refresh_interval
I looked at the syslog file and realized the snmp was unable to access /proc/net amongst other things.
I am not sure if this default config has been fixed for the latest release, but after playing about the the permissions, I have got it to work again.


Linear optimizations model with specified types for variable

Question: Is there any implementation of linear optimization model in python which allows explicitly define the types of my variables. For example I want my variable to be only integers. I can define this when using lpSolve in R like:
<code>    set.type(model, 1:18,type = "integer")
</code>
but I need to build linear optimization model in python.
There is a scipy's linprog implementation but it doesn't allow to define the type of my variables.
Answer: Since IP (Integer Programming) and LP (Linear Programming) are solved with very different algorithms it's legitimate that some solvers don't allow to mix both (IMO): IP has an exponential complexity and LP a polynomial complexity. Your problem is a MILP (Mixed Integer Linear Programming) which has thus an exponential complexity, so you need a MILP solver for Python. But be aware that if you introduce many integer variables even small problem instances might become very hard to solve. Scipy's linprog is just a LP solver according to the documentation.
And by the way it looks like there is also a python interface to lpsolve, and another interface pylpsolve that looks more up to date. I gave pylpsolve a try, and was able to clone from the github repo and install it, you might take a look at this function (according to what I told earlier, you will notice that the names are confusing...)
<code>>>> from pylpsolve import LP
>>> help(LP.setInteger)
</code>


Jenkins. How to change file content

Question: I've created a new project in Jenkins.
But now I want to change some information in my .properties file
How can I do that? (I've already read about Environment Injector, but I don't think, that it's what I need)
So, and one more questions - will this changes commit in file? (I don't want to do that)
Thank you!
Comment: [Content Replace](https://wiki.jenkins.io/display/JENKINS/Content+Replace+Plugin) is a plugin for this purpose.
Answer: Try using a scripted pipeline and you can use groovy for this task. For instance:
<code>Properties props = new Properties()
File propsFile = new File(".properties")
props.load(propsFile.newDataInputStream())
props.setProperty('key', 'value')
props.store(propsFile.newWriter(), null)
</code>
You open the properties file, change the value of a specific key element and write to the same file when done.
Answer: If you are making use of Jenkins and it is on a windows machine. You can make use of PowerShell to change the file content
Here in this example,
I am actually trying to modify the string occurrence 'Memory Usage' with Jenkins build number
<code>(Get-Content C:\proj\Jenkins\workspace\QA.I9.Api\Sample.txt).replace('Memory Usage', $env:BUILD_NUMBER) | Set-Content C:\proj\Jenkins\workspace\QA.I9.Api\Sample.txt
</code>
Thanks,
xyzcoder.github.io

Jenkins. How to change file content