How do I install libpcap-devel on SUSE Enterprise?

Question: I'm new to SUSE and do not understand how to install packages with zypper. Or, rather, I understand you use the "install" subcommand, but it frequently can't find what I'm looking for.
For example, I need libpcap-devel to get the pcap.h headers and the linkable library. The SUSE website says that the package is available, but it doesn't show ups hen I try to install. Meanwhile zypper says it is installed, but the .h file isn't there:
$ sudo zypper install libpcap-dev
Refreshing service 'nu_novell_com'.
Loading repository data...
Reading installed packages...
'libpcap-dev' not found.
Resolving package dependencies...

Nothing to do.
$ sudo zypper search pcap
Refreshing service 'nu_novell_com'.
Loading repository data...
Reading installed packages...

S | Name            | Summary                        | Type
--+-----------------+--------------------------------+-----------
  | libpcap         | A Library for Network Sniffers | srcpackage
i | libpcap0        | A Library for Network Sniffers | package
i | slessp1-libpcap | Recommended update for libpcap | patch
$ sudo zypper install libpcap
Refreshing service 'nu_novell_com'.
Loading repository data...
Reading installed packages...
'libpcap0' providing 'libpcap' is already installed.
Resolving package dependencies...

Suggestions?
Answer: I am suspicious of your nu_novell_com repository. That repository is used by SuSE Linux Enterprise, not openSUSE. Also, the fact you have slessp1-libpcap installed is further evidence you're using an SLE repository not an openSUSE one.
If that's the case, you're using the wrong repo, I'm not terribly surprised you're having problems.
The openSUSE repo for 12.1 (the version you linked to) can be added via:
zypper ar http://download.opensuse.org/distribution/12.1/repo/oss/ OpenSUSE-12.1-OSS
zypper ref

That'll add the repository and refresh it to ensure it has the package list updated. That should help you get at the right libraries for your installation.

Since you are running SLES, you can find out what files did come along with that libpcap0 package through:
rpm -ql libpcap0

Which will give you a list of files. Maybe the .h files you're looking for were stashed some place weird.
Also, you may want to give some thought to looking in the SLE11 SDK. It also has a libpcap0 package, though I'm not 100% sure since I no longer have a licensed SLES install so I can look :P.
Comment: Actually, we're using SuSE Linux Enterprise, not OpenSUSE. I've retagged the question.
Comment: Thanks. We will review SLE11 SDK. We haven't been able to find it online, though, so we're having to mount it from the DVDs. In the meantime, I was able to install from sources at http://www.tcpdump.org/. I'm not sure why that didn't show up the first time I did my search.
Comment: @vy32 Unrelated to this question, but Novell does offer a local repo-mirroring utility (the Subscription Management Toolkit - SMT, if I remember right), that does have the SDK in it. You'll need to be current on support, but it's mighty handy if you have more than a few SLES servers about.
Comment: We ended up giving up one SuSE Linux Enterprise. It wasn't worth the effort.


Finding Compositional Inverses for Formal Power Series

Question: Suppose i have a formal power series
$$f(t)=e^t-1-t=\sum_{k=2}^\infty \frac{t^k}{k!}$$
How would I go about finding its compositional inverse?  Trying to find the inverse of $f(t)=e^t-1-t$ i think is impossible to solve for $t$ w/o using like the Lambert W-function.  However, is there a way to find it using power series?  Perhaps there is a way to extract the coefficients then...
Comment: The compositional inverse of a formal power series can be found using what is known as the Lagrange inversion theorem.
Comment: @Markus Scheuer: Yes, you are right. In this particular case a compositional inverse does not exist.
Comment: Do you mean that you want to find the power series of the inverse for $e^t -t -1$?  Or did you mean in general for any analytic function?
Comment: For the inverse of $e^t-1-t$
Comment: "However, is there a way to find it using power series?" - this amounts to directly finding the series expansion of the Lambert-based function in fact.
Answer: A compositional inverse $g(t)$ of the function $f(t)$ fulfilling $$f(g(t))=t=g(f(t))$$does not exist in the ring of formal power series.

We find in section 5.4 The Lagrange Inversion Formula of Enumerative Combinatorics 2 by R.P. Stanley:

The set  $xK[[x]]$  of all formal power series $a_1x+a_2x^2+\cdots$ with zero constant term over a field $K$ forms a monoid under the operation of functional composition. The identity element of this monoid is the power series $x$.
Recall ... that if $f(x)=a_1x+a_2x^2+\cdots\in K[[x]]$, then we call a power series $g(x)$ a compositional inverse of $f$ if $f(g(x))=g(f(x))=x$, in which case we write $g(x)=f^{\langle-1\rangle}(x)$. The following simple proposition explains
  when $f(x)$ has a compositional inverse.
Proposition 5.4.1 A power series $f(x)=a_1x+a_2x^2+\cdots\in K[[x]]$ has a compositional inverse $f^{\langle-1\rangle}$ if and only if $a_1\ne 0$, in which case $f^{\langle -1\rangle}(x)$ is unique. Moreover, if $g(x)=b_1x+b_2x^2+\cdots$ satisfies either $f(g(x))=x$ or $g(f(x))=x$, then  $g(x)=f^{\langle-1\rangle}(x)$.
Proof. Assume that $g(x)=b_1x+b_2x^2+b_3x^3+\cdots$ satisfies $f(g(x))=x$. We then have
\begin{align*}
\color{blue}{a_1(b_1x}+b_2x^2+b_3x^3+\cdots)
+a_2(b_1x+b_2x^2+\cdots)^2+a_3(b_1x+\cdots)^3+\cdots\color{blue}{=x}
\end{align*}
  Equating coefficients on both sides yields the infinite system of equations
  \begin{align*}
\color{blue}{a_1b_1}&\color{blue}{=1}\\
a_1b_2+a_2b_1^2&=0\\
a_1b_3+2a_2b_1b_2+a_3b_1^3&=0\\
&\vdots\\
\end{align*}
  We can solve the first equation (uniquely) for $b_1$ if and only if $a_1\ne 0$.

Since $a_1=[t^1]f(t)=[t^1](e^t-1-t)=0$ we conclude $f(t)$ has no compositional inverse in the ring of formal power series.
Comment: Great answer! Moreover you can weaken the hp, i.e the compositional inverse is defined even if $b_0 \neq 0$, in such case $f$ has to be a polynomial, so you essentially have two cases to deal with, but it's the same idea.
Comment: @jacopoburelli: Many thanks. Here the author focus on the monoid $xK[[x]]$ as he uses this setting also in the following parts.
Answer: Given $f(x):=e^x-1-x,$ let $\;g(x) := x - 1/6 x^2 + 1/36 x^3 - 1/270 x^4 + 1/4320 x^5 + O(x^6).\;$ The function $\;\sqrt{2f(x)}=x + 1/6 x^2 + 1/36 x^3 + 1/270 x^4 + 1/2592 x^5 + O(x^6)\;$ is its inverse. Thus $h(x):=g(\sqrt{2x}) = \sqrt{2x} - 1/3x + 1/18\sqrt{2x}x -2/135x^2 + O(x^{5/2})\;$ is the Puiseux series inverse of $f(x).\;$ Solve for the coefficients of $\;g(x),\;$ and hence $h(x),\;$ one at a time using either one of the equations $\;f(g(x))=x^2/2\;$ or $\;g(\sqrt{2f(x)})=x.$
Comment: As I can see, you already found the relationship with Puiseux series. :-)


Alterar o atributo do HTML no option com JQUERY

Question: Estou tentando alterar o valor do campo no select com o option para "disabled" mas apenas quando o usuário clicar no campo de input.
Vejam a imagem para entender melhor:

Eu quero exatamente deixar desabilitado o primeiro "option" apenas quando o usuario clicar no campo, estou tentando isso, mas não da certo, estou começando a ver Jquery Agora.
<select id="" class="form-input" placeholder="Categoria: *">
    <option value="categoria" id="#cat">Categoria: *</option>
    <option value="buracos nas ruas">Buracos nas ruas</option>
    <option value="esgoto a ceu aberto">Esgoto a céu aberto</option>
    <option value="lixo em local proibido">Lixo em local proibido</option>
    <option value="falta de iluminação">Falta de iluminação</option>
    <option value="outros">Outros</option>
</select>

$('label select option').click(function(){
    $('#cat').html('<option  disabled >Categoria: *</option>');
});

Se alguém puder me ajudar agradeço imensamente.
Answer: Você está fazendo errado. A primeira option você pode deixar com value="" e colocar o id="cat" (que também está errado: id="#cat") e name="categoria" no select, ficando assim:

<select id="cat" name="categoria" class="form-input">
    <option value="">Categoria: *</option>
    <option value="buracos nas ruas">Buracos nas ruas</option>
    <option value="esgoto a ceu aberto">Esgoto a céu aberto</option>
    <option value="lixo em local proibido">Lixo em local proibido</option>
    <option value="falta de iluminação">Falta de iluminação</option>
    <option value="outros">Outros</option>
</select>

Esse placeholder="Categoria: *" também não precisa. A primeira option é que fará o papel do "placeholder".
No tocante a desabilitar a primeira option ao clicar no select, pode fazer desta forma:

// seleciono o select com id="cat"
// com dois eventos: focus e blur
$('#cat').on('focus blur', function(e){
    $('option:first', this) // selecione a primeira option
    .prop('disabled', e.type == 'focus' ? true : false);
    // desabilito se o evento for focus
    // habilito se o evento for blur
});

<select id="cat" name="categoria" class="form-input" placeholder="Categoria: *">
    <option value="">Categoria: *</option>
    <option value="buracos nas ruas">Buracos nas ruas</option>
    <option value="esgoto a ceu aberto">Esgoto a céu aberto</option>
    <option value="lixo em local proibido">Lixo em local proibido</option>
    <option value="falta de iluminação">Falta de iluminação</option>
    <option value="outros">Outros</option>
</select>


Looking for genres or songs similar to the acoustic guitar part at the end of Black Sabbath's Heaven and Hell

Question: Around the 6:00 mark in the version of the song that can be found here the electric guitars fade out completely and a single acoustic guitar can be heard playing something that I find particularly interesting.
I do not know how to accurately describe the style of this, and with great doubt I throw around the medieval adjective. I'm wondering if there are full songs that are basically just that? That would be great.
Comment: I think this is a legitimate question because it's a chance to talk about a historical style of classical music that has a definite influence on modern metal.
Answer: What you are hearing is two classical guitars (multi-tracked) playing something resembling Renaissance counterpoint, of the sort written in the years between, very roughly, 1400 and 1600. (Medieval would not be the correct term; medieval was an even earlier period in music history.) You can find many recordings of genuine Renaissance lute music. This is what Black Sabbath was trying to emulate. Most of this style of music at that time in history was played on one of the instruments in the lute family, because what we now think of as the classical guitar had not been invented yet. The lute is the ancestor of the modern guitar.
If you want to hear some historical lute music, listen to recordings of artists like Paul O'Dette and Hopkinson Smith.
Comment: Some people use the terms interchangeably, but true medieval music rarely involved any kind of harmony or chords. It was mostly melody and percussion. Ideas like counterpoint and chord progressions evolved as the Medieval period gave way to the Renaissance period and then the Baroque. Very often when you see those fantasy games or movies, the music has been composed in the Renaissance style, so the composer can use counterpoint and chord progressions, which are more familiar to today's listener.
Comment: You can hear the influence of Renaissance and Baroque music in metal and hard rock. Artists like Yngwie Malmsteen, Ritchie Blackmore, Jethro Tull, and many others have incorporated actual Renaissance and Baroque compositions into their songs and guitar solos.
Comment: Thank you. I associated it with the things one usually hears on medieval-themed fantasy games or the like, so that was the first adjective that came to mind. However, I'm having trouble finding compositions that are more similar to what Sabbath recorded. I think slower, and kind of _darker_, maybe? Do you know if any composer's work, contemporary or historical, vaguely fits with that description?
Answer: The part you are referring to is in D# natural minor. Although the natural minor scale (aka Aeolian mode) is commonly found in classical music, this particular piece still sounds pretty modern to me.
For similar music, I would suggest that you listen to Blind Guardian. Their music is mostly Middle-Earth/Lord of the Ring fantasy-themed and very epic. Many pieces are in natural minor. Try The Bard's Song - The Hobbit after 3:08 see if this is what you are looking for and Mordred's Song. They have a whole lot of other fantastic work worth exploring as well.
Classical scales can be found in most power/symphonic/neo-classical metal music such as Blind Guardian, Helloween, Rhapsody of Fire, Yngwie Malmsteen etc. It is a real pleasure to listen to especially when you are a fan of both classical and metal music!


_reactNativeRouterFlux.Actions.create is not a function

Question: I'm using React Native with Redux and React Native Router Flux but I'm getting the following error "_reactNativeRouterFlux.Actions.create is not a function" I followed the docs on the correct setup not sure what's going on
routes reducer
import { ActionConst } from 'react-native-router-flux';

const initialState = {
    scene: {},
};

export default function routesReducer(state = initialState, action = {}) {
    switch (action.type) {
        // focus action is dispatched when a new screen comes into focus
        case ActionConst.FOCUS:
            return {
                ...state,
                scene: action.scene,
            };

        // ...other actions

        default:
            return state;
    }
}

index reducer
export default combineReducers({
    //Scenes,
    routesReducer,
    oauth: oauthReducer,
    navBar: navReducer,
});

my store
const enhancer = compose(
   applyMiddleware(
        thunk,
    ),
);

const store = createStore(
    reducers,
    enhancer,
    autoRehydrate(),
);

app index
// I have the correct imports
const ConnectedRouter = connect()(Router);
import { scenes } from "../app/config/Router";

render() {
        return (
            <Provider store={store} >
                <ConnectedRouter scenes={scenes} />
            </Provider>
        );
    }

my routes
export const scenes = Actions.create(
    <Scene key="root">
        <Scene key="login" component={Login} />
    </Scene>
);

Answer: Sorry, Actions.create way is not supported yet. Could you try
const App = () =>
<Router><Scene key="root">
    <Scene key="Start" component={Start} hideNavBar={true} duration={0}/>
    <Scene key="Login" component={Login} hideNavBar={true}  duration={0}/>
    <Scene key="ChatList" component={ChatList} duration={0}/>
  </Scene>
</Router>

I just ran in to the same problem and found out that this is the only way to solve the issue.  https://github.com/aksonov/react-native-router-flux/issues/1975
Comment: Yes I saw the update, the issue now is that I'm using Redux and there is some error when wrapping the scene in provider  - https://github.com/aksonov/react-native-router-flux/issues/1998


Evaluate $\int_0^{\infty}\mathrm{e}^{-x^{n_1}}\sin(\alpha x^{n_2})\cos(\beta x^{n_3})\,dx$

Question: I was doing a similar looking integral and wanted to ask what will be the general way doing it. I don't know how to go about doing it, can anyone please help?
$$f_{n_1n_2n_3}(\alpha, \beta)=\int_0^{\infty}\mathrm{e}^{-x^{n_1}}\sin(\alpha x^{n_2})\cos(\beta x^{n_3})\,dx$$
$n_1, n_2, n_3, \alpha, \beta \in \mathbb{Z}$
I tried to use the complex number definition of $\sin(x)$ and $\cos(x)$ but then got stuck with the following:
$$\frac{1}{4}\left[\int_0^{\infty}\mathrm{e}^{i\alpha x^{n_2}+i\beta x^{n_3}-x^{n_1}}\,dx+\int_0^{\infty}\mathrm{e}^{i\alpha x^{n_2}-i\beta x^{n_3}-x^{n_1}}\,dx-\int_0^{\infty}\mathrm{e}^{-i\alpha x^{n_2}+i\beta x^{n_3}-x^{n_1}}\,dx-\int_0^{\infty}\mathrm{e}^{-i\alpha x^{n_2}-i\beta x^{n_3}-x^{n_1}}\,dx\right]$$
Comment: Likely no chance: Mathematica fails even with $$\int_0^\infty e^{-x^3}\cos(2x^3)\sin(3x^2)\,dx$$.
Comment: I agree with @user64494 ... there is no reason to think $$\int_0^\infty e^{-x^3}\cos(2x^3)\sin(3x^2)\,dx$$ has a closed form.
Comment: Are $n_1$, $n_2$, $n_3$, $\alpha$, and $\beta$ integers?
Comment: @user64494 I gave that input to wolfram alpha and it gave me the output 0.320266, I don't know but I think that with some luck it would be solvable using generalised fresnel integrals
Answer: The present question generalizes this one to trigonometric functions of an arbitrary monomial argument. There may be no general closed-form expression. If the exponents $n_k$ are non-negative, then the integrand isn't singular. Some particular cases involving polynomial exponentials and trigonometric functions can be found here and there. If $n_1$, $n_2$, $n_3$ belong to $\lbrace 0,1,2\rbrace$, then some other converging integrals may be expressed analytically. Indeed, if the integrand is invariant under $x \mapsto -x$ (i.e., $n_1$, $n_2$ are even integers), then we may rewrite the integral as
$$
f_{n_1n_2n_3}(\alpha, \beta) = \frac12\int_{-\infty}^\infty \exp(-x^{n_1})\sin(\alpha x^{n_2})\cos(\beta x^{n_3}) \, \text d x \, .
$$
Using the trigonometric identity
$$
\sin(\alpha x^{n_2})\cos(\beta x^{n_3}) = \tfrac12 \big(\sin(\alpha x^{n_2}-\beta x^{n_3}) + \sin(\alpha x^{n_2}+\beta x^{n_3})\big)
$$
along with Euler's formula,
the previous integral is rewritten as a linear combination of integrals of the form
$$
I_{a,b} = \int_{-\infty}^\infty \exp\!\big({-x}^{n_1} + \text i\alpha(-1)^a x^{n_2} + \text i \beta(-1)^b x^{n_3}\big) \, \text d x
$$
where $a$, $b$ belong to $\lbrace 0,1\rbrace$. Generalized Gaussian integrals from quantum field theory provide analytic expressions for particular values of $n_1$, $n_2$ in $\lbrace 0,2\rbrace$ and $n_3$ in  $\lbrace 0,1,2\rbrace$.


Nested JSON loadings in D3.js

Question: What is the proper way to do nested loading of JSON files in D3.js. This is the code im trying to use. The problem im having is that d.dataset.toString() return the error Cannot read property 'toString' of undefined.
main.json
<code>[
    {
        "name" : "A-Module",
        "file" : "a.json"
    },
    {
        "name" : "B-Module",
        "file" : "b.json"
    }
]
</code>
a.json
<code>[
    {
        "owner" : "A-Module",
        "dataset" : [1,2,3,4,5,6]
    }
]
</code>
b.json
<code>[
    {

        "owner" : "B-Module",
        "dataset" : [7,8,9,10]
    }
]
</code>

<code>    var width = 500,
        height = 500,
        svg;

    svg = d3.select("body").append("svg").attr("width", width).attr("height",height);

    d3.json("main.json", function(metrics){

        for (var i=0; i<metrics.length; i++){
            var path = metrics[i].file;
            d3.json(path,function(data){
                for(var j=0; j<metrics.length;j++){
                    var owner = data.owner;
                    var metricName = metrics[j].name;

                    if (owner === metricName){
                        metrics[j].dataset = data.dataset;
                    }
                }

            });
        }

        svg.selectAll("g")
        .data(metrics)
        .enter()
        .append("g")
        .append("text")
        .text(function(d,i){
            return d.dataset.toString();
        });
    });
</code>
--- Updated non working example with Queue.js, the problem I now have is that "owner" is undefined.
<code>    var width = 500,
        height = 500,
        svg;

    svg = d3.select("body").append("svg").attr("width", width).attr("height",height);

    d3.json("main.json", function(metrics){
        var tasks = [],
            q = queue(1),
            path;
        for (var i=0; i<metrics.length; i++){
            path = metrics[i].file;
            tasks[i] = function(callback) {
                d3.json(path,function(data){
                    for(var j=0; j<metrics.length;j++){
                        var owner = data.owner;
                        var metricName = metrics[j].name;
                        console.log("1",owner,"2", metricName)
                        if (owner === metricName){
                            metrics[j].dataset = data.dataset;
                            callback(null,data);
                            console.log("THIS SHOULD NEVER PRINT");
                            break;
                        }
                    }

                });
            };
        }
        tasks.forEach(function(t) { q.defer(t); });
        q.awaitAll(function(error, results) {
            svg.selectAll("g")
            .data(metrics)
            .enter()
            .append("g")
            .append("text")
            .text(function(d,i){
                return d.dataset.toString();
            });
        });
    });
</code>
Comment: `d3.json` is asynchronous. [This question](http://stackoverflow.com/questions/16455194/how-to-store-a-json-object-loaded-from-a-file) may help.
Comment: And how do I possible do it if I have one main JSON file which contains 10 difference companies, it stores information about name, adress etc, for each of these 10companies I want to create a g element and fill that g element with name and adress. AND then for each company there exists also a data_companyA.json file containing data I want to use to draw a line graph that should be put in the corresponding company's g element. Could you plz draw up some pseudo code showing how I can do this since I'm totally lost for days now and it sucks :(
Comment: Well you would need nested JSON callbacks or use something like [queue](https://github.com/mbostock/queue).
Comment: Still cant get it to work but have rewritten the question so that it is now obv what im trying to do and how im doing it. Any suggestions?
Comment: It does look like you would want to use queue. Add all the files you need to retrieve and handle the data in the callback.
Comment: Yes it looks like that is what im looking for. However I have problems understanding what I am supposed to save in "tasks", how should the functions look like in this case that I will be saving in tasks? I have added updated code in my question.
Comment: It might be easier to use the first form, i.e. `q.defer(d3.json, url)` for each task and then handle all the data in the `awaitAll` callback.
Comment: But I do not know before hand how many files I am to load? So this is why I cant use the first form.
Comment: I have updated the question again with new code, this time it runs but owner gets no value.
Answer: So i finally got it working. Look at the code below for a working example and read this for more details.
<code>        var width = 500,
            height = 500,
            svg;

        svg = d3.select("body").append("svg").attr("width", width).attr("height",height);

        d3.json("main.json", function(metrics){
            var tasks = [],
                q = queue(),
                paths = [];
            for (var i=0; i<metrics.length; i++){
                paths[i] = metrics[i].file;
            }
            paths.forEach(function(fileName){

                q.defer(function(callback) {
                    d3.json(fileName,function(data){ callback(null, data) });
                });
            });

            q.awaitAll(restOfCode)

            function restOfCode(err, results){
                //Add files into one big file and all the rest of my data bindings
                for(var j=0; j<results.length;j++){
                    for(var k=0; k<metrics.length;k++){
                        var owner = results[j][0].owner ;
                        var metricName = metrics[k].name;
                        if (owner === metricName){
                            metrics[k].dataset = results[j][0].dataset;
                        }
                    }
                }
                svg.selectAll("g")
                .data(metrics)
                .enter()
                .append("g")
                .append("text")
                .text(function(d,i){
                    return d.dataset.toString();
                });
            }
        })
</code>

Nested JSON loadings in D3.js


How do you transform tune or hum in your mind to actual music on guitar

Question: Whenever I heard solos ,especially phrase solos that goes along with some phrase of the song, I wonder how you guys(experienced and professional musician).
Imagine a certain tune or "hum" and translate it to well a spell-boundin music on guitar's fretboard?
How do you know whatever sound you imagined corresponds to the particular fretboard? Is it trial-an error complemented by your past experience
I ask this Because  although I am a beginner who know only few chords and couldn't practice  much due to certain circumstances.
I had a habit of devoting atleast spending an hour just jamming up any notes on any string and with time -being I developed  a certain intuition and I can now vaguely anticipate what a particular fret of the string will sound like ,how it will go along with other note's and most importantly I can now make rough but quite good approximation of tune or hum I imagined(not complicated but simple one)
But I always have feeling that there' something missing(some note or tc)
Does this happen with you guys and how come you fix that 'missing' piece?
Maybe my lack of training and knowledge of music theory the reason?( I didn't know a even basic things like intervals,scales until 3 days before when I started reading the literature on it....)
Comment: They do it the same way as you transform an *idea* that you imagined into your native language - in other words, they just write it down (in music notation), with no more thought than you use when writing words. Of course a five-year-old who is just learning to write can't do that very effectively, and as a "beginner who know only few chords" you are probably in the same situation as the five-year-old, until you learn more!
Comment: A fun "party trick" is to play and sing the same thing at the same time, that's generally a sign that your by-ear playing is getting pretty decent when you can do it reliably.
Comment: >Is it trial-an error complemented by your past experience.  Yes, as someone who can play music by ear, you've pretty much nailed it! But I'll give a more detailed answer below.
Answer: It comes with experience. For example most improvisors have the goal of eventually having a direct connection between their brain and their fingers. A common refrain in jazz study is that you need to learn everything (your instrument, the theory, etc) so well that you eventually forget it—or more accurately no longer need it because you've developed that connection along the way. But it requires a lot of practice and a lot of people never truly get all the way there. That's ok and as Stinkfoot put it "that's what musical growth is about".
But there are few things that will help:

Transcribe—not necessarily in the notation sense, but listen to things you like and figure out how to play them. As you get better, try longer and longer phrases and relying less on tools (ex. ones that slow the music down).
Ear training and sight-singing. Being able to identify melodic intervals is key. Musictheory.net has free ear training exercises. And doing the opposite—singing known intervals—helps as well. A proper solfege course/book where you're singing from notation is great but if you don't read music or don't want to go that deep at least try singing a bit. Sit at a piano or with your guitar and try singing things like intervals, arpeggios, scales, or short melodies that you already know how to play (or once you learn them). Sing it first given only the starting note as reference and then play it after see how close you came.
Melodic (scales, arpeggios, etc) training on your instrument while singing along. Knowing how to identify intervals is not much help unless you connect that to your instrument by playing them. And singing the note name and/or chord/scale degree helps make the mental connection between what your fingers are doing, what you're hearing/thinking, and the theory (the note name, the interval, the arpeggio, etc).
Answer: A good exercise is to train your ear to recognize intervals. Have someone play an interval while you're not looking. Name the interval, and play it on your guitar.  (There are most likely apps that will play random intervals for you.) If you get to where toy can recognize and play intervals just by hearing them, you're well on your way to playing the melodies in your head.
Answer: For me, anyway, it's mainly practice and experience.
Practice, because your pitch recognition gets better and better.  This can not be overemphasised.  Sitting down and trying to work out how to play "twinkle twinkle little star" or "Oh Christmas tree" or something like that is incredibly valuable to your musical development.  Translating familiar melodies (the more familiar and simpler the better) is a great place to start, in training your ears to relate your subjective experience of pitch and melody, to an objective understanding of what those notes actually are.
That's something that comes with practice; the more you use it, the better your pitch recognition is.
So for example, if you sing me any 2 notes in sequence, then I'll be able to tell you what the interval between them is.  That comes with practice. If you play 8 random notes at me, one after the other, then I'll be able to play them back to you.  That's practice.  If I hear a song on the radio, I'll be able to play the melody back to you, more or less the first time.  That's both practice and experience.
Practice because that gives you good pitch and interval recognition as I outlined above, but also experience, in that the more you play and work out music by ear, the more you start to recognise patterns that notes often fall into.  On top of that, as well as hearing each note in relation to the one that came before it (which is what I'd be doing with a series of 8 random notes), you relate it to the music context it comes in. It's easier to work out things that fall into patterns you understand and recognise.
Put it this way, imagine you were trying to acquire the skill of copying photographs.  You would obviously get better at painting in general over time, better at manipulating the brush, better at understanding how to produce the colour and lighting that you want with paint.  But you would also get better at painting specific things, better at painting trees, better at painting water, better at painting sunlight etc.  Because you'd be doing the same sorts of shapes each time.  Reading books about how to paint trees certainly would help you progress faster, but most important would just be the practice!  And of course, let's say I give you a photograph and you have to copy it from memory, without looking (which is more like what working out music is like, unless you are spamming the replay button like a m*****f***a).  A painting of something you recognise, and know how to paint would be much easier to reproduce then something you'd never seen before!
So, to give a simple example, if you listen to a lot of blues music, you'll notice that there are certain licks that are often used to end a phrase, and certain chord changes and flourishes which pop up again and again, and with different little variations.  So then when you go to play along with a blues song, when you hear a phrase that's the same, or similar, or related to something you already know well, you don't have to work it out from scratch because you already know what it is.  More abstract from that, you start to notice more more generalised principles of what kinds of notes tend to go together in what context, and what those contexts all sound like, and so as well as recognising specific note patterns, you also recognise a sort of "framework" of possibilities based on what the music sounds like.
Formal music theory can help this of course, you might here a melody and go "oh that's an ascending major scale starting on the third, with a flat 7 passing tone" or whatever.  But it still all comes down to playing real music by ear, and theory is only as good as how it relates to your actual subjective understanding of the music you're hearing and playing.  Theory can then give you ways to abstract and analyse and make sense of that music, which is of course useful because it allows you to see even more patterns, some of which you might not have noticed on your own.
The real benefit of getting good at playing by ear, is that you get music theory lessons for free, all the time.  Whenever you properly listen to music, and pay attention, you notice notes and chords as they come, and so it's impossible not to learn a little about ho music works just from hearing music played.  Of course, I'm not saying you hear every single note of every complex piece of music, and the more complex and more unfamiliar music is, the less of it that you pick up just from listening, but of course, that's where the practice part comes in!
Answer:
Does this happen with you guys and how come you fix that 'missing'
  piece?

I think it happens to everyone, each on their own level. For both musicians and composers, that's mostly what musical growth is about: Figuring out how to express the music in your head on your instrument, or capture it in the form of notes to be written down and played by musicians, in order to express what's in your musical mind. "Find the missing pieces" and capture them, as it were.
There are lots of ways to "fix it". As a musician, ultimately everything you learn about  music is to facilitate your ability to express yourself eloquently through your instrument.
Having said that, ear training, as mentioned by @Xasel is a very important skill.
Another very good thing to do in your case is to copy on your instrument parts that you like from recordings. Get down that lick or solo that you like and absorb it - understand how it sounds and how it works when you play it. When you do your own thing, those memories will be there to help you navigate.
Transcribing, which requires the ability to read and write music well, can also help you a great deal, as many have attested to.

Maybe my lack of training and knowledge of music theory the reason?

(Pretty obvious, but perhaps worth saying anyhow: Training and theory are not necessarily the same thing. You can be trained in how to play without learning much theory. )
I don't want to open a whole can of worms by delving into your question on theory,  but training and knowledge of theory certainly won't hurt you if you don't let them get in your way (take them as guidelines, not rules)  but they don't guarantee anything either.
The only guarantees are your innate talent (since you intuitively know that "something is missing" you clearly have musical talent) and your motivation to leverage that talent.


Serialism and the the twelve-tone period

Question: I'm really confused about 'Serial composers'. While studying Igor Stravinsky, in his later life, he was regarded as a 'Serial composer'. I would love to know if composers despised this categorisation but we are digressing.
From his Wiki page, from 1945-1968.

This began Stravinsky's third and final distinct musical period, the serial (or twelve-tone) period, which lasted until his death.

Not just Igor, there are lots of them.

Source: Google search
When we say 'twelve-tone' we mean the Chromatic scale don't we?

The twelve Major and Minor's aside - this is a new scale, a scale which uses all the notes.
However, when Stravinsky was setting about his work or any composer of that matter it's up to you what notes you use, you could use all twelve notes in any scale but this doesn't class you as a Serial Composer does it? I could have a piece in G Major and still use whatever I wanted to with the use of accidentals and naturals?
In a way, we are always writing music using Serialism then? I must admit I'm not very good with scales yet, I don't know them off the top of my head :(

All 12 notes are thus given more or less equal importance, and the music avoids being in a key.

What is it about this movement, of which people believe Schoenberg's use was of it was most important, made it such a worthwhile landmark in the evolution of classical music?
Comment: This question is very probably too specialized for MusicFans.
Answer: The key word here is serialism.
Serialism means that the compositional process is determined by a series, or list, of pitches and various transformations that occur to this series.
A twelve-tone serialist will create a listing of all twelve pitches, using each once and only once. They can use this series (also known as a row), but they can also:

Transpose it to begin at different pitch levels.
Retrograde it and play it backwards.
Invert it and play it upside down.
Or some combination of all of these, like a transposed retrograde inversion (!).

Thus there are several points in the compositional process where the composer does not choose the next pitch; rather, that next pitch is chosen for them based on the serial transformations they chose earlier.
Earlier composers did use all twelve pitches, but they used them in a tonal context. Here, Stravinsky is using all twelve pitches with the serial process, which is the main difference.
As for why this is important in music history, it's one of the key developments (forgive the unintentional pun) in composing music without a tonic pitch. As composers like Wagner and Mahler continually pushed the boundaries of tonal music, Schoenberg felt that the only logical next step was to abandon tonality completely. One way of doing this was to use the serial process.
And one final historical tidbit: Stravinsky hated serialism for decades. But once Schoenberg died, Stravinsky suddenly loved serialism. It seems that his "hatred" for serialism was really a hatred for Schoenberg, and once the latter died, the former felt comfortable using serialism publicly!
Comment: As always, Richard - thanks very much. I did read that Stravinsky and Schoenberg had respect for each other but did not particularly like each other. Schoenberg was known for making fun of Stravinsky and his love of the C Major scale.
Comment: Another great line from Schoenberg "My music is not modern, it is merely badly played".


Função Keyup no input ao carregar um modal

Question: Estou implementando uma função para alterar a senha do usuário logado.
Quando eu carrego a senha do usuário no componente input ele não valida a senha carregada, a qual está fora da regra estabelecida pela função abaixo.
Gostaria que, ao carregar o modal, a senha já fosse validada. Atualmente a minha função só valida quando eu apago os dados do componente e volto a dar o foco.
Alguém poderia me ajudar ??
Essa é a minha função em JS:
$('#inpSenha').keyup(function() {
  var value = $(this).val();
  var letras,
    numeros,
    letrasMaiusculas,
    especial;

  if (/[a-z]/gm.test(value)) {
    letras = " ";
  } else {
    letras = "Letras minúsculas";
  }
  if (/[0-9]/gm.test(value)) {
    numeros = "  ";
  } else {
    numeros = "Números";
  }
  if (/[A-Z]/gm.test(value)) {
    letrasMaiusculas = "  ";
  } else {
    letrasMaiusculas = "letras maiúsculas";
  }
  if (/[!@#$%*()_+^&{}}:;?.]/gm.test(value)) {
    especial = "  ";
  } else {
    especial = "Caracteres especiais não alfaNuméricos";
  }

  $('p').html("A senha deve possuir: " + letras + "|" + numeros + "|" + letrasMaiusculas + "|" + especial)
});

Meu componente está assim:

        <button type="button" class="close" data-dismiss="modal">×</button>

           Preferências

        <form novalidate="novalidate" data-toggle="validator" name="frmUsuario" id="formCadastro" role="form">

                  <input class="hide" type='file' id="inputFile" onchange="readURL(this);" />

              Login:
              <input maxlength="20" disabled="disabled" type="text" class="form-control" ng-model="usuario.login" />

              Nome:
              <input maxlength="30" type="text" class="form-control" ng-model="usuario.nome" />

              E-mail:
              <input maxlength="100" type="email" class="form-control" ng-model="usuario.email" />

              Senha:
              <input id="inpSenha" required="required" type="password" class="form-control" ng-model="usuario.senha" autofocus="autofocus" />
              A senha deve conter pelo menos um número.

              A senha deve conter pelo menos uma letra maiúscula.

              A senha deve conter pelo menos uma letra minúscula.

              A senha deve conter no mínimo 6 caracteres.

              A senha deve conter pelo menos um caractere especial não alfanumérico.

        </form>

        <button style="background-color: #b51e27;  color: white;" type="button" class="btn btn-default " id="btnSalvar" data-dismiss="modal" ng-click="salvarUsuario()">Salvar</button>
        <button style="background-color: #b51e27; color: white;" type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>

Comment: @MatheusMiranda Funcionou perfeitamente!! põe como resposta. Obrigado !
Comment: Inclua mais conteúdo do seu html e js, está um tanto confuso para compreender o comportamento atual e o que você deseja
Comment: Eduardo segue jsfiddle: http://jsfiddle.net/1aeur58f/1013/.
Comment: Fiz outro código, olha na minha resposta como ficou., ele valida a senha ao carregar modal.
Answer: Este evento é disparado quando o modal foi tornado visível para o usuário:
$('#modalAlterarUsuario').on('shown.bs.modal', function (e) {
  // seu código js
});

Segue exemplo em jsfiddle:
http://jsfiddle.net/1aeur58f/1014/
Ou pode fazer isso:
$(document).on('#modalAlterarUsuario','shown.bs.modal', function (e) {
   // seu código js
});

Comment: pode acrescentar o document em seu codigo $(document).on('#modalAlterarUsuario','shown.bs.modal', function (e) {
  // seu código js
});
Answer: Olá @eduardo-krakhecke!
Creio que você pode conseguir melhor resultado separando a função de validação e chamando-a tanto no evento keyup quanto no evento show da modal. Se você estiver usando um framework (como Bootstrap) para criar sua modal, você pode chamar a função de validação no evento apropriado (show) e adaptá-la para ser atribuída ao valor do seu campo de senha (eu não encontrei no HTML que você citou algo parecido com um campo de senha...).
Enfim, creio que sua função de validação pode receber o elemento como parâmetro ao invés de ficar isolada num elemento específico, assim fica modular.
Veja se isto pode ser útil: https://jsfiddle.net/GustavoAdolfo/xakhc5av/
O que acha de fazer esse teste e nos falar o resultado?
Sucesso!


Binding Source Filter not working in DGV

Question: I'm having a problem with the binding source on a DGV .  The message is "DataMember Property 'nodes' cannot be found on the dataSource " The column count is 14 after setting the table to the datasource.  The error occurs on the line   nodesDataGridView.DataSource = bsNodes. If I break before the error and then hover on the ds it does show that table nodes is in the datasource. I've used code similiar to this to setup other DGV's and I don't see any difference in this one.
if I remove these statements, I don't get the error but of course it is not filtered):
<code>        nodesDataGridView.DataSource = bsNodes
        bsNodes.Filter = "company_number = " & Globals.customer_id
</code>
I should probably mention that I added company_number after the grid was completed and working.  It was setup for a single company code but now I'm having to add the requirement to support multiple companies in the database.
Any ideas?
Thanks,
Vic
<code>' Setup objects for loading the summary grid
Dim sqlNodes As String = "Select *From nodes order by display_sequence"
Dim comm As MySqlCommand = New MySqlCommand(sqlNodes, m_cn1)
Dim daNodes As MySqlDataAdapter = New MySqlDataAdapter(comm)
Dim dsNodes As DataSet = New DataSet()
dim bsNodes As New BindingSource

    Try
        AddHandler ButtonSaveChanges.Click, AddressOf ButtonSaveChanges_Click
        dsNodes.Clear()
        daNodes.Fill(dsNodes, "nodes")
        m_cn1.Close()
        nodesDataGridView.DataSource = dsNodes
        nodesDataGridView.DataMember = "nodes"
        bsNodes.DataSource = dsNodes.Tables("nodes")
        Debug.Print("nodes column count is " & nodesDataGridView.ColumnCount)
        nodesDataGridView.DataSource = bsNodes
        bsNodes.Filter = "company_number = " & Globals.customer_id

    Catch ex As Exception
        MessageBox.Show("Failed to load summary grid" & vbCrLf & vbCrLf & ex.ToString)
    End Try
</code>
Comment: I'm still trying to get this to work - does anyone know why this is failing?  I am really stuck!
Answer: try to filter like this
<code>bsNodes.Filter = "company_number = '" & Globals.customer_id.ToString() & "'"
</code>
EDIT:
<code>    bsNodes.DataSource = dsNodes.Tables("nodes")
    nodesDataGridView.DataSource = bsNodes '<- you set dsNodes(Dataset) this should be the BindingSource not Dataset
    nodesDataGridView.DataMember = "nodes"
    Debug.Print("nodes column count is " & nodesDataGridView.ColumnCount)
    'nodesDataGridView.DataSource = bsNodes
    bsNodes.Filter = "company_number = '" & Globals.customer_id.ToString() & "'"
</code>
Comment: Spajce, thanks for the answer but the error occurs prior to setting the filter. Also, company_number is an int field.
Comment: i modified my answer.. i added `ToString()` so the integer will convert to string.
Comment: I'm getting the error "DataMember Property 'nodes' cannot be found on the dataSource " before I set the filter on the binding source.  Look at my original description of the problem.
Comment: ok try to check again.. you should set the `BindingSource` to `DataGridView.DataSource` not the `DataSet`
Comment: That was it ...   Thanks spajc I really appreciate your help in solving this!


Lazy load module with Router Guard with dynamic routes in Angular4

Question: I have single lazy load module with multiple components having dynamic routes each component define by router guard.So how to configure routes for each component having dynamic routes . For every route path i am able to see the same component and when i route manually using url am getting error "Guard is not a function".
Below is my code:
mycomponent.module.ts
<code>@NgModule({

    imports: [
        routing,
        SharedModule,
        CommentsModule,
    ],
    declarations: [
                    MyComponent1,
                    MyComponent2,
                    MyComponent3,
                    MyComponent4,
                    MyComponent5,
    ],
    providers: [mycomponentService]

})
export class MyComponentModule { }
</code>

mycomponent.routing.ts
<code>const routes: Routes = [
    {
        path: '',
        canActivate: [AuthGuard],
        canActivateChild: [AuthGuard],
        children: [
            { path: '/my-todos', component: MyComponent1 },
            { path: '/edit-my-todo/:tid', component: MyComponent2 },
            { path: '/edit-my-todo/single-todo/:tid', component: MyComponent2 },
            { path: '/edit-my-todo/multi-todo/:tid', component: MyComponent2 },
            { path: '/add-todo', component: MyComponent3 },
            { path: '/multiple-todo-details/:tid', component: MyComponent4 },
            { path: '/todo/:alias', component: MyComponent5 },
            { path: '/todo-preview/:tid', component: MyComponent5 },
        ]
    },
];
</code>

app.routing.ts
<code> {
    path: '',
    loadChildren:'app/mycomponent/mycomponent.module#MyComponentModule'
};
</code>
How to configure routes for this dynamic routes, even I am facing error of gaurd is not a function. Does anyone know how to configure routes for above. Does anyone face the same issue before. Any help would be great help. Thank you in advance for the help.
Answer: I figured out, the way of configuring the routes. Hope this helps someone in future
mycomponent.routing.ts
<code>     const routes: Routes = [
        { path: 'my-todos', component: MyComponent1 },
        { path: 'edit-my-todo/:tid', component: MyComponent2 },
        { path: 'edit-my-todo/single-todo/:tid', component: MyComponent2 },
        { path: 'edit-my-todo/multi-todo/:tid', component: MyComponent2 },
        { path: 'add-todo', component: MyComponent3 },
        { path: 'multiple-todo-details/:tid', component: MyComponent4 },
        { path: 'todo/:alias', component: MyComponent5 },
        { path: 'todo-preview/:tid', component: MyComponent5 },
</code>
];
app.routing.ts
<code> {
       path: '',
       canActivate: [AuthGuard],
       canActivateChild: [AuthGuard],
       children: [
                   { path: '',
                     loadChildren:
                     'app/mycomponent/mycomponent.module#MyComponentModule'
                   },
                ],
  }
</code>
This is working fine and works well.


Why wont drupal recognize my base table name?

Question: So I have been playing around with the poll module in Drupal8-beta14 and I just upgraded the site to RC1.  I am trying to uninstall the poll module now but i get this error everytime
exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown      [error]
column 'base_table.id' in 'field list'' in
/srv/www/dtadev2/core/lib/Drupal/Core/Database/Statement.php:64

the only place i can find the string "base_table"  in the poll module at all is in the @ContentEntityType annotation
 @ContentEntityType(
 *   id = "poll",
 *   label = @Translation("Poll"),
 *   handlers = {
 *     "access" = "\Drupal\poll\PollAccessControlHandler",
 *     "storage" = "Drupal\poll\PollStorage",
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler",
 *     "list_builder" = "Drupal\poll\PollListBuilder",
 *     "view_builder" = "Drupal\poll\PollViewBuilder",
 *     "views_data" = "Drupal\poll\PollViewData",
 *     "form" = {
 *       "default" = "Drupal\poll\Form\PollForm",
 *       "edit" = "Drupal\poll\Form\PollForm",
 *       "delete" = "Drupal\poll\Form\PollDeleteForm",
 *       "delete_vote" = "Drupal\poll\Form\PollVoteDeleteForm",
 *       "delete_items" = "Drupal\poll\Form\PollItemsDeleteForm",
 *     }
 *   },
 *   links = {
 *     "canonical" = "/poll/{poll}",
 *     "edit-form" = "/poll/{poll}/edit",
 *     "delete-form" = "/poll/{poll}/delete"
 *   },
 *   base_table = "poll",
 *   data_table = "poll_field_data",
 *   admin_permission = "administer polls",
 *   field_ui_base_route = "poll.poll_list",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "question",
 *     "uuid" = "uuid",
 *       "category" = "category",
 *     "langcode" = "langcode"
 *   }
 * )

So all I can think of is that for some reason when uninstalling the module Drupal is supposed to use poll but is take base_table instead.
Is this something in RC1 or is there an easy syntax error I am missing?
edited to add the backtrace info
    exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column            [error]
'base_table.id' in 'field list'' in /srv/www/dtadev2/core/lib/Drupal/Core/Database/Statement.php:64
Stack trace:
#0 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Statement.php(64): PDOStatement->execute(Array)
#1 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Connection.php(615):
Drupal\Core\Database\Statement->execute(Array, Array)
#2 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(73):
Drupal\Core\Database\Connection->query('SELECT base_tab...', Array, Array)
#3 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Query/Select.php(481):
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT base_tab...', Array, Array)
#4 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(262):
Drupal\Core\Database\Query\Select->execute()
#5 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(89):
Drupal\Core\Entity\Query\Sql\Query->result()
#6 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(74):
Drupal\Core\Entity\Query\Sql\Query->execute()
#7 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentUninstallValidator.php(47):
Drupal\Core\Entity\ContentEntityStorageBase->hasData()
#8 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(539):
Drupal\Core\Entity\ContentUninstallValidator->validate('poll')
#9 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(343):
Drupal\Core\Extension\ModuleInstaller->validateUninstall(Array)
#10 /srv/www/dtadev2/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(95):
Drupal\Core\Extension\ModuleInstaller->uninstall(Array, true)
#11 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(227):
Drupal\Core\ProxyClass\Extension\ModuleInstaller->uninstall(Array)
#12 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(80):
drush_module_uninstall(Array)
#13 /home/ubuntu/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1190): _drush_pm_uninstall(Array)
#14 [internal function]: drush_pm_uninstall('poll')
#15 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(364):
call_user_func_array('drush_pm_uninst...', Array)
#16 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(215): _drush_invoke_hooks(Array,
Array)
#17 [internal function]: drush_command('poll')
#18 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(183):
call_user_func_array('drush_command', Array)
#19 /home/ubuntu/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#20 /home/ubuntu/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#21 /home/ubuntu/.composer/vendor/drush/drush/drush.php(11): drush_main()
#22 {main}

Next exception 'Drupal\Core\Database\DatabaseExceptionWrapper' with message 'SQLSTATE[42S22]: Column not
found: 1054 Unknown column 'base_table.id' in 'field list': SELECT base_table.id AS id, base_table.id AS
base_table_id
FROM
{poll} base_table
GROUP BY base_table.id
LIMIT 1 OFFSET 0; Array
(
)
' in /srv/www/dtadev2/core/lib/Drupal/Core/Database/Connection.php:676
Stack trace:
#0 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Connection.php(640):
Drupal\Core\Database\Connection->handleQueryException(Object(PDOException), 'SELECT base_tab...', Array,
Array)
#1 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(73):
Drupal\Core\Database\Connection->query('SELECT base_tab...', Array, Array)
#2 /srv/www/dtadev2/core/lib/Drupal/Core/Database/Query/Select.php(481):
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT base_tab...', Array, Array)
#3 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(262):
Drupal\Core\Database\Query\Select->execute()
#4 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/Query/Sql/Query.php(89):
Drupal\Core\Entity\Query\Sql\Query->result()
#5 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(74):
Drupal\Core\Entity\Query\Sql\Query->execute()
#6 /srv/www/dtadev2/core/lib/Drupal/Core/Entity/ContentUninstallValidator.php(47):
Drupal\Core\Entity\ContentEntityStorageBase->hasData()
#7 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(539):
Drupal\Core\Entity\ContentUninstallValidator->validate('poll')
#8 /srv/www/dtadev2/core/lib/Drupal/Core/Extension/ModuleInstaller.php(343):
Drupal\Core\Extension\ModuleInstaller->validateUninstall(Array)
#9 /srv/www/dtadev2/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(95):
Drupal\Core\Extension\ModuleInstaller->uninstall(Array, true)
#10 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(227):
Drupal\Core\ProxyClass\Extension\ModuleInstaller->uninstall(Array)
#11 /home/ubuntu/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(80):
drush_module_uninstall(Array)
#12 /home/ubuntu/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1190): _drush_pm_uninstall(Array)
#13 [internal function]: drush_pm_uninstall('poll')
#14 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(364):
call_user_func_array('drush_pm_uninst...', Array)
#15 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(215): _drush_invoke_hooks(Array,
Array)
#16 [internal function]: drush_command('poll')
#17 /home/ubuntu/.composer/vendor/drush/drush/includes/command.inc(183):
call_user_func_array('drush_command', Array)
#18 /home/ubuntu/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#19 /home/ubuntu/.composer/vendor/drush/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#20 /home/ubuntu/.composer/vendor/drush/drush/drush.php(11): drush_main()
#21 {main}

describe poll shows this
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| pid   | int(11) | NO   | PRI | 0       |       |
+-------+---------+------+-----+---------+-------+

Comment: Enable verbose error reporting (if you can't access the UI anymore at all, see sites/example.settings.local.php). Then post the full error here. Also ,when exactly does this happen, on every request or on specific actions only?
Comment: if i use drush to uninstall the module or i go to any page with involving the poll.  so anyting like /admin/content/poll/ breaks it.  I have added the entire error. I think this is what you are looking for?
Comment: Can you execute "describe poll;" with drush sql-cli or similar and post the output here ? The error happens as part of the content check, which wants to prevent that you uninstall the poll module if there is data left. But apparently your poll table is messed up and doesn't look like it should.
Comment: describe poll resutls are posted.  ill look into your other link posted.  Thanks!
Answer: Whatever the exact reason is, this is another variant here:

Improperly deployed missing entity table breaks module uninstall

Not being able to uninstall a module when storage is messed up.
You could start a patch for that by adding a try/catch around the hasData() call in ContentUninstallValidator and ignoring the problem. No table or messed up table likely also means no data ;)
There might be additional errors after that, where you need similar fixes.
Answer: Explanation
The error means that id column is missing in your base table (poll) and it happens during uninstall process where ContentUninstallValidator::validate (part of Entity) determines the reasons a module can not be uninstalled and it fails.
This issue is further explained in the following bug report:

ContentEntityStorage base has a hasData() method that checks if any entities exist at all. This method is called during the uninstall process of a module to warn the user that data will be lost if the module is uninstalled.
When a module has deployment issues and the entity storage table has not been created, the hasData() method will throw an exception, completely blocking the uninstall process. So basically you end up with a broken module, that you cannot uninstall.

This is the code which fails in validate():
if ($module == $entity_type->getProvider() && $entity_type instanceof ContentEntityTypeInterface && $this->entityManager->getStorage($entity_type->id())->hasData()) {
  $reasons[] = $this->t('There is content for the entity type: @entity_type', array('@entity_type' => $entity_type->getLabel()));
}

Workaround
One workaround is to recreate the missing field, truncate table and uninstall the module again, e.g.
drush sqlq 'ALTER TABLE poll ADD COLUMN id INT(11)'
drush sqlq 'TRUNCATE TABLE poll'
drush -y pm-uninstall poll

Warning! By truncating you're removing all the data in that table,
so backup it before if required.
Source: SQL Error on redirect uninstall.

Solution
To fix this problem completely, please apply the patch attached in the below bug report:

Improperly deployed missing entity table breaks module uninstall


HTML5 custom data attributes in Drupal

Question: I want to use the "data" attribute in some of my tags, and I have been searching for a way to include it.
For Example: I am adding JavaScript code to my form. I use hook_form_alter() and the #attached property.
$path = drupal_get_path('module', 'mymodule');
$form['#attached']['js'][] = array('data' => $path . '/js/custom_values.js','type' => 'file');

How do I add a "data" attribute to the

HTML5 custom data attributes in Drupal


Selecting ARIMA orders based on ACF-PACF vs. auto.arima

Question: I use R to fit an ARIMA model to a time series (yearly granularity):
library(forecast)

beer <- c(150,241,361,403,504,684,706,862,879,806,840,846,1024,1196,1239,1237,1281,1342)

ts_beer = ts(beer, start = c(1980), frequency = 1)

dif.ts_beer <- diff(ts_beer)

acf(dif.ts_beer)
pacf(dif.ts_beer)

Based on the ACF and PACF, I fit an ARIMA(4,0,4) model.
dif.ts_beer.fit <- arima(dif.Gas, order = c(4,0,4))

dif.ts_beer.fit

It looks OK. But then I run auto.arima:
auto.arima(dif.ts_beer)

It gives:
Series: dif.ts_beer
ARIMA(0,0,0) with non-zero mean

Coefficients:
         mean
      70.1176
s.e.  17.0359

sigma^2 estimated as 5242:  log likelihood=-96.4
AIC=196.81   AICc=197.67   BIC=198.48

So the manual ARIMA(4,0,4) is not a good choice for this case? If so, what ARIMA(p,d,q) model should I use?
Comment: While I agree fully with @Stephen_Kolassa, for academic interest you may want to explore EACF plots. EACF is extended ACF proposed by Tsay, R. and Tiao, G. (1984). It is available in TSA package in r. See [here](https://www.rdocumentation.org/packages/TSA/versions/1.2/topics/eacf)
Answer: First, it is very hard to use (P)ACF plots to identify ARIMA(p,d,q) models if both p and q are nonzero. See Hyndman & Athanasopoulos:

If p and q are both positive, then the plots do not help in finding suitable values of p and q.

Second, your peaks at lag 4 only barely exceed the confidence bands.
I would always prefer auto.arima() over parsing (P)ACF plots myself, i.e., the Box-Jenkins approach. It is built by experts with a lot of experience, and it truly is a gold standard for ARIMA modeling, unless you are an expert yourself and you are working academically on the frontiers of knowledge.
In the present case, auto.arima() would prefer a simple mean model. I would recommend that you run with this.
Comment: @Stephan_Kolasa, thank you Mr. Klassa for the detail explanation and guidance on the matter. It benefits a lot!
Comment: Great @StephanKolassa


Find the curve, given that $r'(t) = Cr(t)$

Question: I need to find the curve, given that $r'(t) = Cr(t)$ (where $C$ is a constant), for all real $t$ and $r(0)=i+2j+3k$.
To start, I know that the equation I will need is the
$$K=\frac{||r'(t) \times r''(t)||}{||r'(t)||^3}.$$
However, I'm not sure how to get what I currently have $(r'(t))$ into $r(t)$ so that I can plug the values into the equation. Any help would be greatly appreciated!
Comment: You can solve $r(t)$ explicitly (solving the ODE)
Comment: Like mich95 did below.
Comment: @John I haven't done calculus in quite a while, remind me of how that is possible, please?
Comment: @John what about ti+2tj+3tk? Is this what you're talking about?
Comment: You don't need that formula for $K$. Separate $r$ into components and solve for each separately; it's a simple ODE.
Comment: @HomegrownTomato But how would I solve for the actual curve by just separating r into components? Could you also give me an example of this, I'm not exactly sure what you mean by "separating it into components and solving each separately"
Comment: @HomegrownTomato Ah, okay that makes sense. Thanks. However, simply having r(t) doesn't give us the curvature. I know that using the formula for K here is extremely messy, but how else would I be able to find curvature without using it? Thank you.
Comment: Well, if you need the curvature, you should now apply the formula for curvature to the found solution. It wasn't clear that you needed it. The question said "I need to find the curve,"
Comment: @HomegrownTomato Sorry, yes, I meant the curve. I thought the curve was also found using that equation.
Comment: @HomegrownTomato Ah, nevermind. I figured it out. Clearly all the calc I'd learned back in 2013 completely moved out of my brain.
Answer: $r'(t)=Cr(t)$ implies $(x'(t),y'(t),z'(t))=C(x(t),y(t),z(t))$  So $x(t)=K_{1}e^{Ct}$, $y(t)=K_{2}e^{Ct}$ $z(t)=K_{3}e^{Ct}$ with $x(0)=1$, $y(0)=2$, $z(0)=3$, where $K_{1}$, $K_{2}$ $K_{3}$ re constants to determine.$x(0)=1$ then $K_{1}=1$, similarly, $K_{2}=2$, $K_{3}=3$. So I think $r(t)=e^{Ct}i+2e^{Ct}j+3e^{Ct}k$
Answer: If you only need the curvature, then solving isn't necessary.
Note that
$$ \textbf{r}''(t) = C\textbf{r}'(t)$$
Thus
$$ K = \frac{||\textbf{r}' \times C\textbf{r}'||}{||\textbf{r}'||^3} = 0 $$


np.where on pd.DataFrame for dictionary of non-zero indicies

Question: I'm trying to make a nearest neighbors thing that's super super fast.  Right now I'm using networkx then iterating through all the G.nodes() then  S = set(G.neighbors(node)) then S.remove(node) which works pretty well but I want to get better at indexing and taking advantage of datastructures.  I'd like to move away from iterating when possible.
I ultimately want to end of up with a dictionary object where key is root_node and value is a set of node neighbors (not including the root_node)
Here's what my graph and DF_adj adjacency matrix looks like:

When I do np.where(DF_adj == 1) the output is 2 arrays that looks like:
(array([ 0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,
        3,  3,  3,  4,  4,  4,  5,  5,  5,  6,  6,  6,  7,  7,  7,  8,  8,
        8,  9,  9, 10, 10]), array([ 0,  1,  3,  4,  5,  7,  0,  1,  2,  3,  4,  6,  8,  9, 10,  1,  2,
        0,  1,  3,  0,  1,  4,  0,  5,  6,  1,  5,  6,  0,  7,  8,  1,  7,
        8,  1,  9,  1, 10]))

Checked out this but it didn't help me completely
Python pandas: select columns with all zero entries in dataframe
def neighbors(DF_adj):
    D_node_neighbors = defaultdict(set)
    DF_indexer = DF_adj.fillna(False).astype(bool) #Don't need this for my matrix but could be useful for non-binary matrices if someones needs it
    for node in DF_adj.columns:
        D_node_neighbors[node] = set(DF_adj.index[np.where(DF_adj[node] == 1)])
        D_node_neighbors[node].remove(node)
    return(D_node_neighbors)

How can I use np.where on the entire pd.DataFrame to get this type of output?
defaultdict(set,
            {'a': {'b', 'd', 'e', 'f', 'h'},
             'b': {'a', 'c', 'd', 'e', 'g', 'i', 'j', 'k'},
             'c': {'b'},
             'd': {'a', 'b'},
             'e': {'a', 'b'},
             'f': {'a', 'g'},
             'g': {'b', 'f'},
             'h': {'a', 'i'},
             'i': {'b', 'h'},
             'j': {'b'},
             'k': {'b'}})

Comment: You can't, `np.where()` ain't gonna return a dictionary.
Comment: I know but there might be a more efficient way that I'm thinking then iterating through all of the columns indvidually
Answer: You can do it with comprehension dict. If df is :
   a  b  c  d  e  f  g  h  i  j  k
a  1  1  0  1  1  1  0  1  0  0  0
b  1  1  1  1  1  0  1  0  1  1  1
c  0  1  1  0  0  0  0  0  0  0  0
d  1  1  0  1  0  0  0  0  0  0  0
e  1  1  0  0  1  0  0  0  0  0  0
f  1  0  0  0  0  1  1  0  0  0  0
g  0  1  0  0  0  1  1  0  0  0  0
h  1  0  0  0  0  0  0  1  1  0  0
i  0  1  0  0  0  0  0  1  1  0  0
j  0  1  0  0  0  0  0  0  0  1  0
k  0  1  0  0  0  0  0  0  0  0  1

Then {i:{ j for j in df.index if df.ix[i,j] and  i!= j} for i in df.index } is :
{'j': {'b'},
 'e': {'a', 'b'},
 'g': {'b', 'f'},
 'k': {'b'},
 'a': {'b', 'd', 'e', 'f', 'h'},
 'c': {'b'},
 'i': {'b', 'h'},
 'f': {'a', 'g'},
 'b': {'a', 'c', 'd', 'e', 'g', 'i', 'j', 'k'},
 'd': {'a', 'b'},
 'h': {'a', 'i'}}

Or  2X faster:
s=df.index
d=collections.defaultdict(set)
for (k,v) in zip(*where(df==1)):
    if k!=v:
        d[s[k]].add(s[v])

Comment: `1 loop, best of 3: 4.75 s per loop
1 loop, best of 3: 2.41 s per loop` on my fastest one (the nx.graph) yours was twice as fast. Thanks man this is really helpful


Twitter-bootstrap carousel - ease in out AND fade background color on slide

Question: I seem to be able to get it to slide or fade colors but not both.  Trying to make it slide in from the right and transition between different background colors.
Jsfiddle:
jsfiddle.net/HEzuM/3/
Answer: I managed to do this with some fiddling. Can see my solution here: jsfiddle.net/HEzuM/4/


GServer receive messages

Question: I use the code below to create a TCP/IP server and then the client code to call it but for some reason the server doesn't receive the message sent by the client. Please advise. Thanks
Server:
class MyServer < GServer
  def initialize(port=20607, host=GServer::DEFAULT_HOST)
    super(port, host, Float::MAX, $stderr, true)
  end

  def serve(sock)
    begin
      @clients << sock
      stock.accept
      message = sock.gets.chomp
      puts "message: " << message
      this.stop if message == "#quitserver"
      # TODO: code that process commmands comes here
    rescue

    ensure
      @clients.delete(sock)
    end
  end
end

Client:
require 'socket'
streamSock = TCPSocket.new( "127.0.0.1", 20607 )
puts "Socket created..." unless streamSock.nil?
sleep 5
streamSock.puts "hello world"
sleep 5
streamSock.close
puts "Socket closed."

Answer: oops my mistake, @clients array isn't declared. Now working :)

GServer receive messages


Where is the xml file generated saved after running xmlrunner?

Question: I have my unittest suite and this piece of code. Where is the xml file saved?
<code> if __name__ == '__main__':
     unittest.main(verbosity=2, testRunner=xmlrunner.XMLTestRunner(filename='test-reports.xml'))
</code>
Thanks in advance
Comment: For this to work, xml should be in the same directory of this python file (your current working directory)
Answer: The problem was that I was running the tests with PyCharm's predefined running settings for unittest, however this requires the following command to run and generate the files:
<code>python -m <name-of-the-test>
</code>


Find $\displaystyle\lim_{x \rightarrow 0} \frac{\tan x+\tan 2 x+\ldots+\tan n x}{\operatorname{arctg} x}$

Question: Estimate limit: $$\displaystyle\lim_{x \rightarrow 0} \frac{\tan x+\tan 2 x+\ldots+\tan n x}{\arctan x}.$$
I understand correctly that the tangent and arctangent of an infinitesimal argument are equivalent to it, so instead of $\arctan x $, I can write $\tan x$?
Comment: To simplify, solve for the limit of $$\frac{\tan kx}{\arctan x}=\dfrac{\frac{\tan kx}x}{\frac{\arctan x}x}$$
Comment: You can certainly use: $$\frac{\arctan x}{\tan x}\to1,$$ if you have that result. This lets you replace $\arctan$ here with $\tan.$
Comment: No, $\sin[x^2)/x\to 0.$ I dislike the word "replace" here, because you can't **always** replace $\arctan x$ with $\tan x$ in a limit. For example the limit $$\frac{\arctan x-x}{x^3}$$ won't allow such substitution. But $\frac{\tan x}{\arctan x}\to 1$ means that if the numerator or denomination of a limit is exactly $\arctan x,$ we can do such a replacement.
Comment: @ThomasAndrews Oh, that's convenient. Thanks!
Comment: @ThomasAndrews Is it possible if x->0 to replace sin(x^2) with x?
Answer: By the asymptotic relations:
$$\lim_{x\to 0}\frac{\tan(\alpha\cdot x)}{\alpha \cdot x}=1$$
And:
$$\lim_{x\to 0}\frac{\arctan(x)}{x}=1$$
So, the numerator becomes:
$$\tan(x)+\tan(2x)+\dots+\tan(nx)\sim x+2x+\dots+nx\,\,\, x\to 0$$
Thus the limit:
$$\lim_{x \to 0} \frac{\tan x+\tan(2x)+\ldots+\tan(nx)}{\arctan(x) }=\lim_{x\to 0}\frac{x\cdot \frac{n\cdot (n+1)}{2}}{x}=\frac{n\cdot (n+1)}{2}$$
Comment: @CatMario: absoltely not. Namely: $$\lim_{x\to 0}\frac{\tan(x)}{x}=\lim_{x\to 0}\frac{\sin(x)}{x}\cdot \frac{1}{\cos(x)}=1$$ So: $$\lim_{x\to 0}\frac{\sin(x^2)}{x}=0$$
Comment: Is it possible if x->0 to replace sin(x^2) with x?
Comment: @Matteo $\sin(x^2)/x\to 0,$ not $\infty.$
Comment: @ThomasAndrews: Ops, sorry. My mistake. Corrected.


how to print this pattern using python iterator

Question: L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'

suppose we can and can only get the iterator of some iterable(L).
and we can not know the length of L.
Is that possible to print the iterable as:
'head123tail'
'head456tail'
'head789tail'
'head10tail'

My try at it is as follows.
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'
slice_size = 3

i = iter(L)
try:
    while True:
        counter = 0
        while counter < slice_size:
            e = next(i)
            if counter == 0:
                print(head, end='')
            print(e, end='')
            counter += 1
        else:
            print(tail)
except StopIteration:
    if counter > 0:
        print(tail)

Comment: You'll have to buffer your 'head', and print it only after next has succeeded, since you can't predict what's next in an iterator without consuming it.
Comment: @ Jacques, thanks for your suggestion. I modify my preliminary question.
Answer: Here's one way to do it with itertools.groupby and itertools.count.
groupby on the key function lambda _: next(c)//3 groups the items in the iterables in threes  in successions. The logic uses the integer division of the next object in the count item on 3:
from itertools import groupby, count

L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'

c = count()
for _, g in groupby(L, lambda _: next(c)//3):
    item = head + ''.join(map(str, g)) + tail
    print(item)

Output:
head123tail
head456tail
head789tail
head10tail

Comment: That's a very interesting application of `groupby` and `count`. You might also post this as an answer to [this](http://stackoverflow.com/questions/24527006/split-a-generator-into-chunks-without-pre-walking-it) more general question.
Comment: I don't know how to choose between the current two answers. So I `timeit`. I ran them on my slow computer for 1000 times. Koledoye's answer got 2.9803745844324028 seconds; tobias_k's got 8.567057737782685 seconds.
Comment: @tobias_k Thanks for the pointer. Added an answer: http://stackoverflow.com/a/40063403/3125566
Comment: @minion You could at least upvote the answers if you're still not sure of which to accept
Comment: @MosesKoledoye, would you slightly change your answer, since my question is 'we can only get the iterator of some iterable(L).'
Comment: @minion you do `it = iter(L)`, and pass the iterator to groupby. But this would be redundant as an iterator can work directly
Comment: @MosesKoledoye, yes, I know. I just think the answer might be better to completely fit the question. Thanks for your wonderful answer.
Answer: You can split the iterator into chunks of three, using chain and slice from itertools and a for loop, and then join them. The for loop will do most of what your try/while True/except construct is doing.
L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head = 'head'
tail = 'tail'
slice_size = 3
iterator = iter(L)

from itertools import chain, islice
for first in iterator:
    chunk = chain([first], islice(iterator, slice_size - 1))
    print(head, ''.join(str(x) for x in chunk), tail)

However, if your iterator is just a list, you can just use range with a step parameter:
for start in range(0, len(L), slice_size):
    chunk = L[start : start + slice_size]
    print(head, ''.join(str(x) for x in chunk), tail)


3rd iterate of a continuous function equals identity function

Question: If $ f: \mathbb{R} \to \mathbb{R} $ is continuous, and $\forall x \in \mathbb{R} :\;(f \circ f \circ f)(x) = x  $, show that $ f(x) = x $.
The condition that $f$ is continuous on $\mathbb{R}$ is crucial for the proof. I can find functions such as $\displaystyle\frac{x-3}{x+1}$ that satisfies  $ (f \circ f \circ f)(x) = x $.
I have tried to negate the conclusion to see if there's a contradiction, but got stuck.
Comment: Possibly relevant nitpick: $(x-3)/(x+1)$ isn't a function $\mathbb{R} \to \mathbb{R}$
Comment: might be generalised to $f(x)=\frac{x+b}{x+a}$, with $a^2+a+(1+b)=0$ and $a+1\neq 0$. See [here](http://tinyurl.com/84trljm).
Comment: I suppose you can remedy that issue by extending it to send $-1 \to -1$.
Answer: Pick any $x$ and look at the three numbers $x,f(x),f(f(x))$.
If any two of them are equal, then they are all equal by applying $f$ and using $ f \circ f \circ f = id$, and so $x = f(x) = f(f(x))$.
So suppose they are distinct.
Without loss of generality, you can assume $x$ to be between $f(x)$ and $f(f(x))$ (if it's not, pick $f(x)$ or $f(f(x))$ in place of $x$).
Then, by the intermediate value theorem, there exist a number $y$ between $x$ and $f(x)$ such that $f(y) = x$. Then, $y = f(f(f(y))) = f(f(x))$, which is impossible because $f(f(x))$ cannot be between $x$ and $f(x)$ ($x$ is between the other two)
Comment: Nice you did not used the whole continuity, but only the intermediate value theorem which holds for derivatives.
Comment: @Merico, I am not getting the part that why  $y$ cannot be between $x$ and $f(x)$, can you please help me out?
Comment: for example if $f(x) < x < f(f(x))$ then there is a $y$ such that $f(x) < y < x$ and $f(y)=x$. Then $y < x < f(f(x))$ so $y < f(f(x))$. But $y = f(f(f(y))) = f(f(x))$ and so $y < y$ which is impossible.
Answer: First note that $f$ must be either increasing or decreasing by the intermediate value theorem, as if $f(x)=f(y)$ then $x=f(f(f(x)))=f(f(f(y)))=y$. Suppose $f$ is increasing. Suppose we have some $a\in\mathbb R,\epsilon_1>0$ such that $f(x)>x$ for all $x\in(a,a+\epsilon_1)$. Pick some $0<\epsilon_2<\epsilon_1$ such that $f(x)\in (a,a+\epsilon_1)$ for all $x\in (a,a+\epsilon_2)$, which must exist as $\lim\limits_{\epsilon_2\to 0^+}f(a+\epsilon_2)-(a+\epsilon_2)=0$ and for $\epsilon_2<\epsilon_1$ the expression in the limit is positive. Do the same for $0<e_3<e_2$ such that $f(x)\in (a+\epsilon_2)$ for $x\in (a,a+\epsilon_3)$. Then
$$a+\epsilon_3/2=f(f(f(a+\epsilon_3/2)))>f(f(a+\epsilon_3/2))>f(a+\epsilon_3/2)>a+\epsilon_3/2$$
which is a contradiction. The same can be done if we have $f(x)<x$ for $x\in (a,a+\epsilon_1)$, so $f(x)-x$ cannot be positive or negative on any open interval, hence by continuity it cannot be positive or negative anywhere in $\mathbb R$ by continuity, hence $f(x)=x$ for all $x$. To conclude, we note that $f$ cannot be decreasing, as the same procedure gives us $f(x)=-x$ for all $x$, so $f(f(f(x)))=-x\neq x$.
Comment: After assuming that f is increasing (strictly), if there is x such that f(x)>x we can have the immediate contradiction: f(f(x))>f(x) and x=f(f(f(x))) > f(f(x)) > f(x) > x just by the fact that f(x) is increasing. (Same for f(x)<x).
Answer: Let's consider the case of the circle. Your example, continuously extended to the projective line (i.e. the circle) by $f(-1) = \infty$ and $f(\infty) = 1$ really is a continuous function satisfying $f(f(f(x))) = x$.
Let $f$ be any continuous function of the circle satisfying $f(f(f(x))) = x$ but not $f(x) = x$ identically. Suppose $a$ is not a fixed point. Then, $a$, $b = f(a)$, and $c = f(b)$ are three different points.
Since $f$ is continuous and invertible, I claim that it must send the directed arc $ab$ (the one that doesn't pass through $c$) to the directed arc $bc$, and also $bc \mapsto ca$ and $ca \mapsto ab$.
I assert that every continuous function on the circle satisfying $f(f(f(x))) = x$ identically  that is not $f(x) = x$ is of the above form. Conversely, any choice of $a, b, c$ and choice of invertible orientation preserving maps $ab \mapsto bc$ and $bc \to ca$ has this property.
In particular, each such function has no fixed points.
Now, back to the line. If $f$ is a continuous function satisfying $f(f(f(x))) = x$, then it is invertible, and we can extend it to a continuous function of the circle by $f(\infty) = \infty$. This also satisfies $f(f(f(x))) = x$ and has a fixed point -- therefore $f$ satisfies $f(x) = x$.
In the end, it's probably the same underlying idea as mercio had, but I still thought it interesting to treat the circle anyways.


Qgis extremely slow on averything

Question: My Qgis is behaving terribly slow the last few months. Opening takes minutes, trying to switch between the layers panel and the browser panel takes minutes, selecting an arcgis featurelayer takes minutes, trying to add data takes minutes, closing takes minutes. Pretty much everything takes a long, long time.
I tried removing Qgis and all asociated files and re-installing it, but no luck. I tried a fresh profile: no luck.
What else can I do?
Answer: I also had this issue, especially with switching between Layers and Browser panel. I solved this with acitivating Fast Scan this directory option from the context menu in the Browser panel for all the hard drives I'm using.

Qgis extremely slow on averything


Why "countability" in definition of Lebesgue measures?

Question: According to Wikipedia, the definition of the Lebesgue outer measure of a set $E$ is as follows:
$$
\lambda^*(E) = \operatorname{inf} \left\{\sum_{k=1}^\infty l(I_k) : {(I_k)_{k \in \mathbb N}} \text{ is a sequence of open intervals with } E\subseteq \bigcup_{k=1}^\infty I_k\right\}
$$
Suppose we remove the countability requirement:
$$
\lambda^*(E) = \operatorname{inf} \left\{\sum_{I \in X} l(I) : X \text{ is a set of open intervals with } E\subseteq \bigcup_{I \in X} I\right\}
$$
(Where we could just define $\sum_{I \in X} l(I)$ to be $\operatorname{sup} \left\{\sum_{I \in Y} l(I) : Y \text{ is a finite subset of } X \right\}$.)
Why would this not work? What would break if we remove the countability requirement?
Comment: In a finite sum the number of nonzero terms cannot be uncountable.
Comment: Possible duplicate of [What happens if an uncountable collection of intervals is used in the definition of the Lebesgue outer measure?](http://math.stackexchange.com/questions/1332279/what-happens-if-an-uncountable-collection-of-intervals-is-used-in-the-definition)
Comment: In the Caratheodory generalization for constructing outer measures, where the family of sets we start with may not be open intervals, it is sometimes important that only countable covers are allowed.  For example if we have single points allowed, but all have value zero.
Answer: If $\sum_{I \in X} l(I)=\infty$, then there is a countable subset of $X$ that sum up to infinity too.
If $\sum_{I \in X} l(I)<\infty$, then only countably many terms of $l(I)$ is non-zero.
In either case, it'd just be the same as allowing only countable infinite terms.
Comment: Suppose $\Sigma_{I \in X} l(I) = S < \infty$. There are at most 2 terms of the sum with $l(I) \ge S/2$. There are at most $3$ terms with $l(I) \ge S/3$. There are at most $4$ terms with $l(I) \ge S/4$. And so on...
Comment: Do you have a proof of why your second claim is true?
Comment: @chell Yes I do. It's kind of a common knowledge but I'll find you the link.
Comment: @chell Here's some more detailed answers to that question of yours http://math.stackexchange.com/questions/70194/does-uncountable-summation-with-a-finite-sum-ever-occur-in-mathematics/70195#70195 and http://math.stackexchange.com/questions/1413874/can-we-add-an-uncountable-number-of-positive-elements-and-can-this-sum-be-finit/1413886#1413886.
Answer: It will work. The thing is, if $X$ is uncountable the sum is necessarily infinite. Thus only countable families $X$ will give approximations to the infimum, if it is indeed finite.
Answer: As long as you are working with the reals, keep in mind that there is a countable basis of open sets for the topology, specifically the collection of open intervals with rational endpoints.  Any open set in the topology can be written as a union of sets from this basis.  So your set $\cup_{I\in X} I$ can be written as a countable union (since there are only countably many sets in the basis) of open intervals (probably different from the intervals in $X$) from the basis.  In the definition, the $\inf$ must be realized by a countable union of open intervals, because any union of open intervals (in fact any open set) is equivalent to a union of open intervals from this countable basis, so necessarily a countable union.  As others have already pointed out, this doesn't work in more general spaces, hence the need to be specific in the definition, but for the reals, there is no need for more than a countable collection of intervals.
Comment: Note that your proposal doesn't always work in every second-countable spaces because while it is true that every open set can be written as a union of countable bases, the bases need not be disjoint.
Answer: The answer is much simpler that given above. Firstly, the sum of a collection of nonnegative reals (even uncountable) is defined as the supremum of its finite `sub-sums.' However, in your comment:
(Where we could just define $\sum_{I \in X} l(I)$ to be $\sup\{\sum_{I \in Y} l(I):\ Y \text{ is a finite subset of } X\}$.)
the point is that the collection $\{I \in Y\}$ in general does not cover the set $E$, so, the corresponding finite sum does not appear in ``your'' version of an outer measure.
Secondly, if the set $E$ is unbounded, the only way you can cover it by a finite number of interval is when one of them is unbounded - but then the sum of their lengths will equal $\infty$. So, all unbounded sets (e.g. the integers) have infinite your outer measure.
Finally, it is not too difficult to verify that for a bounded set $E$, your outer measure of $E$ coincides with the ('classical') Lebesgue measure of the topological closure of $E$ (this closure is compact in that case).
Comment: Copied from an "answer": Sorry, my previous answer deals with the version of `finite' collections of intervals - I haven't seen earlier that the discussion is about arbitrary collections. Of course, the above answers are correct. I'm sorry for my oversight.


Dúvida sobre Expressão Regular

Question: Boa noite a todos.
Gostaria de saber de uma expressão regular para obter as seguintes informações:
Numeração e título de um capítulo.
Exemplo:

INTRODUÇÃO

número = 1.
título = INTRODUÇÃO
1.1. OBJETIVO GERAL
número = 1.1.
título = OBJETIVO GERAL
1.2. OBJETIVO ESPECÍFICO
número = 1.2.
título = OBJETIVO ESPECÍFICO
Preciso disso para gerar um sumário no seguinte formato:

|  INTRODUÇÃO         | PÁGINA

1.1. | OBJETIVO GERAL      | PÁGINA
1.2. | OBJETIVO ESPECÍFICO | PÁGINA
Ou seja, a expressão regular deverá ser capaz de reconhecer números seguido de pontos, no seguinte formato genérico:
Título Primário => x.
Título Secundário => x.x.
Título Terciário => x.x.x.
Título Quaternário => x.x.x.x.
E assim por diante.
Desde já agradeço a atenção. Abraço a todos.
Comment: Tentastes alguma ? E também dependendo, pode usar algum DOM parser...
Comment: Tentei esta: @"[\d]+[.]

Porém só está pegando o primeiro número e o primeiro ponto.
Comment: Esqueci de mencionar, estou utilizando a linguagem C#.
Comment: Utilizei este site: http://rubular.com/r/v5TNAzCQKa

Nele funciona, mas na hora de programar na aplicação está dando errado...
Comment: A propósito, o que é DOM parser? Procurei aqui e não encontrei ...
Comment: Peri, qui a pouco aparece...
Comment: Mas -- em que formato está o seu texto aí? Você sabe que o mais comum é o contrário, né? Marcaçoes especiais no texto do que é título, capítulo, etc... geram os números (e aí geram os títulos).
Comment: A resposta postada resolve o seu problema. Para testar expressões, use essa ferramenta online: http://www.regexr.com/
Answer: Essa expressão regular aqui resolve:
"^\s*?(?P<numero>(\d\.)+)\s*(?P<titulo>.*)$"

Você não disse que ferramenta vai usar para aplicar a expressão regular - esta pode ter alguma coisa específica das expressões regulares de Python - onde testei a mesma. A documentação está em: https://docs.python.org/3/library/re.html
Num prompt interativo de Python 3.5:
In [47]: import re

In [48]: a = """
    ...: 1.INTRODUÇÃO
    ...: número = 1.
    ...:
    ...: título = INTRODUÇÃO
    ...:
    ...: 1.1. OBJETIVO GERAL
    ...:
    ...: número = 1.1.
    ...: título = OBJETIVO GERAL
    ...:
    ...: 1.2. OBJETIVO ESPECÍFICO
    ...:
    ...: 1.2.1. Detalhamento
    ...: 2. Outro Capítulo
    ...: """

In [49]: [(m.group('numero'), m.group('titulo')) for m in re.finditer(r"^\s*?(?P<numero>(\d\.)+)\s*(?P<titulo>.*)$", a, re.MULTILINE) ]
Out[49]:
[('1.', 'INTRODUÇÃO'),
 ('1.1.', 'OBJETIVO GERAL'),
 ('1.2.', 'OBJETIVO ESPECÍFICO'),
 ('1.2.1.', 'Detalhamento'),
 ('2.', 'Outro Capítulo')]

(A função re.finditer devolve um iterador de "match objects" - esses por sua vez tem um método group que pode ser chamado com o nome do grupo desejado. O nome dos grupos, por sua vez, é dado dentro da própria expressão regular, usando a construção (?P<nome>...) )
Essa parte dos nomes dos grupos deve ser a única coisa que muda caso a ferramenta de regexp que você for usar seja diferente das regexps de Python.)
Comment: A partir do seu exemplo consegui obter a seguinte expressão regular que me atendeu:

^\s*((\d\.)+)

A partir dela teve como obter os números dos capítulo.

Muito obrigado jsbueno.

Dúvida sobre Expressão Regular


.htaccess https rewrite for single domain on multisite installation

Question: I have a multisite installation with 2 sites running off separate domains. One of these sites needs to go through https:// while the the other can stick to http://. I also want all traffic to be rewritten to include the www. prefix.
So:
example.com rewritten to https://www.example.com
example.co.uk rewritten to http://www.example.co.uk
I'm trying to set my .htaccess file to handle this, and have tried with the  syntax discussed here.
RewriteEngine on
<If "%{HTTP_HOST} == 'example.com'">
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>
<If "%{HTTP_HOST} == 'example.co.uk'">
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !http
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</If>

Needless to say, it's not working. Any input would be much appreciated!
Answer: First I would try using the [drupal]/sites/sites.php file to do something like this:
$sites['example.co.uk'] = 'example.com';
$sites['example.com'] = 'example.com'; // for demonstration only

Then check out the htaccess module to force HTTPS. These are the  options:
Answer: This is untested, but would the following work:
# Force HTTPS for example.com
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [NC,R=301,L]

# Force HTTP for example.co.uk
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} !^(www\.)?example\.co\.uk$ [NC]
RewriteRule ^(.*)$ http://www.example.co.uk/$1 [NC,R=301,L]

Comment: Hi Colin, thanks a lot for your answer. Unfortunately that's not working either. Looking at it with an htaccess tester it is rewriting the URL to https://www.example.com/example.com

I've tried a few more things and have a version that works on the htaccess tester, but returns an infinite loop once it's up on the server and I try it there:
Comment: #.com to https://www
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) https://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) https://www.example.com/$1 [R=301,L]

#.co.uk to http://www
RewriteCond %{HTTP_HOST} ^example\.co\.uk$ [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.example.co.uk/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.example\.co\.uk$ [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://www.example.co.uk/$1 [R=301,L]
Comment: Think your loop is caused by missing the RewriteCond %{HTTPS} lines
Answer: My suggestion is don't change anything except redirect http://example.com to https://example.com with following (
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

And if you like to redirect https://example.co.uk  to http://example.co.ukadd the following line to your.htaccess` file ( but I don't think you need them)
RewriteCond %{HTTP_HOST} ^(www.)?example.co.uk$
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

Also, you can try to set them with Htaccess module

Htaccess is a module which autogenerates a Drupal root htaccess file
  based on your settings.
Drupal tries to provide a one size fits all htaccess for Apache
  webservers, but this goal is increasingly difficult. This module
  allows the webmaster to set specific options.
Also, this module is dedicated to webmasters who don't want to
  manually modify htaccess every time during a version upgrade to use
  Drupal.

Features:
 - Set redirection to www or non www.
 - Use Followsymlinks or SymlinksIfOwnersMatch.
 - HTTPS support (redirect all request to HTTPS or support both protocols).
 - Protect core text files (like CHANGELOG.txt) from being viewed.
 - Ability to insert Boost htaccess settings
 - Add custom rules before Drupal rules.
 - Each htaccess is attached to a profile. This way, you can manage several
 - htaccess files and deploy the right one to your website.
 - Check if htaccess is altered and report in site status .
 - List item
 - Drush integration.


Consulta Linq com count

Question: Estou fazendo uma consulta que possui alguns joins e um count, porém quero fazer ela com Linq.
Está é minha Query.
sbSQL.Append("SELECT grproj.cdgruproj as  Id, grproj.dsgruproj as DescricaoGrupoProjeto, ");
            sbSQL.Append("(SELECT COUNT(*) ");
            sbSQL.Append("        FROM usufrm ");
            sbSQL.Append("        WHERE usufrm.cdfrm = form.cdfrm ");
            sbSQL.Append("        AND usufrm.sgproj = proj.sgproj ");
            sbSQL.Append("        AND usufrm.tpproj = tproj.tpproj ");
            sbSQL.Append("        AND usufrm.dtcan IS NULL) as QuantidadeDeUsuarios ");
            sbSQL.Append("FROM grproj  ");
            sbSQL.Append("INNER JOIN proj ON grproj.cdgruproj = proj.cdgruproj ");
            sbSQL.Append("INNER JOIN tproj ON proj.tpproj = tproj.tpproj ");
            sbSQL.Append("INNER JOIN projfr ON proj.sgproj = projfr.sgproj AND proj.tpproj = projfr.tpproj ");
            sbSQL.Append("INNER JOIN form ON form.cdfrm = projfr.cdfrm ");
            sbSQL.Append("WHERE grproj.dtcan IS NULL AND proj.dtcan IS NULL AND form.dtcan IS NULL ");

Esse é o exemplo da minha consulta com Linq, o campo quantidade deve ser um count:
 IList<GrupoProjetoEntity> grupos = (from grupoProjeto in session.Query<GrupoProjetoEntity>()
                                       join projeto in session.Query<ProjetoEntity>() on grupoProjeto.Id equals projeto.cdgruproj.Id
                                       join tipoProjeto in session.Query<TipoProjetoEntity>() on projeto.tpproj.TipoProjeto equals tipoProjeto.TipoProjeto
                                       join projetoFormulario in session.Query<ProjetoFormularioEntity>() on
                                       new { SiglaProjeto = projeto.sgproj, tpproj = projeto.tpproj.TipoProjeto }
                                       equals new { SiglaProjeto = projetoFormulario.sgproj, tpproj = projetoFormulario.tpproj.TipoProjeto }
                                       join formulario in session.Query<FormularioEntity>() on projetoFormulario.cdfrm.Id equals formulario.Id
                                       select new GrupoProjetoEntity()
                                       {
                                           Id = grupoProjeto.Id,
                                           DescricaoGrupoProjeto = grupoProjeto.DescricaoGrupoProjeto,
                                           QuantidadeDeUsuarios = 0
                                       }).ToList();

Answer: Tenta fazer uma subquery e pegar o Count dela:
IList<GrupoProjetoEntity> grupos = (from grupoProjeto in session.Query<GrupoProjetoEntity>()
    join projeto in session.Query<ProjetoEntity>() on grupoProjeto.Id equals projeto.cdgruproj.Id
    join tipoProjeto in session.Query<TipoProjetoEntity>() on projeto.tpproj.TipoProjeto equals tipoProjeto.TipoProjeto
    join projetoFormulario in session.Query<ProjetoFormularioEntity>() on
    new { SiglaProjeto = projeto.sgproj, tpproj = projeto.tpproj.TipoProjeto }
    equals new { SiglaProjeto = projetoFormulario.sgproj, tpproj = projetoFormulario.tpproj.TipoProjeto }
    join formulario in session.Query<FormularioEntity>() on projetoFormulario.cdfrm.Id equals formulario.Id
    let contagem = (
                    from usuario in session.Query<UsuarioEntity>()
                    where usuario.cdfrm == formulario.cdfrm
                    where usuario.sgproj = projeto.sgproj
                    where usuario.tpproj = tipoProjeto.tpproj
                    where usuario.dtcan == null
                   ).Count()
    select new GrupoProjetoEntity()
    {
       Id = grupoProjeto.Id,
       DescricaoGrupoProjeto = grupoProjeto.DescricaoGrupoProjeto,
       QuantidadeDeUsuarios = contagem
    }).ToList();

Comment: Muito boa Miguel, por mais que tenha ficado lenta, a consulta funcionou.
Comment: Que coisa não... tenta usar `let` pra calcular o valor do `Count` antes do `new`... pode ser que ao usar o operador `Count` dentro do `new` ele esteja fazendo vários Count.
Comment: Também pode ver qual é a query que está sendo gerada e executada no banco de dados usando algum profiler de BD.
Comment: Então, a consulta no banco é instantanea, acho que pelo excesso de joins vou tentar usar let e te falo.
Comment: Beleza, se ficar mais rápido eu altero a resposta pra deixar ela o melhor possível.
Comment: COmo seria essa consulta com o let? ele serve para agrupar?
Comment: `let` é só uma variável no meio da query, que pode ser usada depois. Alterei a resposta, mas verifica ai. Se não funcionar eu volto como estava antes.
Comment: Não mudou muita coisa na velocidade, acho que vou partir pra um HQL, ou algo mais rapido. Muito Obrigado Miguel!!
Comment: Como mencionou HQL, suponho que esteja usando o NHibernate. [Existem formas de ver a query que ele está executando no BD](http://stackoverflow.com/questions/129133/how-do-i-view-the-sql-that-is-generated-by-nhibernate)(está em Inglês)... assim fica mais fácil de saber o que está acontecendo por debaixo dos panos.

Consulta Linq com count


Pointing SSL domain from Cloudflare to Azure Storage static website

Question: I have created an Azure Static website using azure storage account and then I have pointed CNAME record to the primary web link provided under the Static Website section in the Azure Storage account. My domain name is connected with Cloudflare to provide with SSL for my domain but even its SSL enable I get the error saying "This site is not secure" in the address bar padlock sign location. What is the reason to happen this ?
Answer: You either need to add a custom hostname to the storage account or set a page rule in cloudflare that rewrites the host headers.