Python 2.7 on Ubuntu

Question: I am new to Python and am working on a Linux machine (Ubuntu 10.10). It is running python 2.6, but I'd like to run 2.7 as it has features I want to use. I have been urged to not install 2.7 and set that as my default python.
My question is, how can I install 2.7 and run it side by side with 2.6?
Answer: I did it with pythonbrew on my Ubuntu 10.10 machine.
$ python -V
Python 2.6.6
$ curl -kL https://raw.github.com/utahta/pythonbrew/master/pythonbrew-install | bash
$ . $HOME/.pythonbrew/etc/bashrc
$ pythonbrew install 2.7.1
$ pythonbrew switch 2.7.1
Switched to Python-2.7.1
$ python -V
Python 2.7.1

I also used it to install Python 3.2.
Comment: what  does the line . $HOME/.pythonbrew/etc/bashrc do?
Comment: I agree, [pyenv works great](http://oylenshpeegul.typepad.com/blog/2013/08/acme-envy.html)!
Comment: also, should i not setup pythonbrew to always be useable? doesn't that mean i need to... um, do something? if i log out and log in again, my pythonbrew is forgotten about. i think that line above has something to do with it... but what?
Comment: You're right, that line sets up pythonbrew by running all the commands in that file. Just add that line to your .bashrc file so that it happens every time.
Comment: This really helped me too! Thanks
Answer: I recently backported Python 2.7 to Debian squeeze. Since Ubuntu 10.10 is newer than Debian squeeze, if you can do it on squeeze, you can certainly do it on Ubuntu. I don't have access to a Ubuntu 10.10 system. If I set one up, I'll test on it, and update this answer. So, here instead is a brief sketch of what I did on Debian.
First, a general and obvious comment, but something that is easily overlooked. One should not take the listed build dependencies of a Debian package too seriously. They may be far more specific than needed. For example, software like Python, which is designed to be portable and run over a wide array of systems, is unlikely to build depend on very specific versions of software. The runtime dependencies can be adjusted as well, but this should be done with more caution. However, runtime dependencies are mostly generated dynamically based on software that is already on this system, so usually that is not a big issue.
apt-cache policy python2.7
python2.7:
  Installed: 2.7.2-8
  Candidate: 2.7.2-8
  Version table:
     2.7.2-12 0
         50 http://debian.csail.mit.edu/debian/ unstable/main i386 Packages
     2.7.2-8 0
         50 http://debian.csail.mit.edu/debian/ testing/main i386 Packages
 *** 2.7.2-8 0
        100 /var/lib/dpkg/status

Selecting the testing version we get
apt-get source python2.7=2.7.2-8

Looking at debian/control, we see the following build dependency lines.
Build-Depends: debhelper (>= 5), quilt, autoconf, libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), tk8.5-dev, zlib1g-dev, blt-dev (>= 2.4z), libssl-dev, libexpat1-dev, sharutils, libbz2-dev, libbluetooth-dev [linux-any], locales [!armel !avr32 !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [linux-any], netbase, lsb-release, bzip2, libdb4.8-dev, gdb, python, help2man
Build-Depends-Indep: python-sphinx
Build-Conflicts: tcl8.3-dev, tk8.3-dev, tcl8.4-dev, tk8.4-dev, python2.7-xml, python-xml, autoconf2.13, libncurses5-dev
Most of this is easily satisfied on squeeze. With the handy utility apt-show-versions we get on my machine
apt-show-versions debhelper quilt autoconf libreadline-dev libtinfo-dev libncursesw5-dev tk8.5-dev zlib1g-dev blt-dev \
libssl-dev libexpat1-dev sharutils libbz2-dev libbluetooth-dev locales libsqlite3-dev \
libffi-dev mime-support libgpm2 netbase lsb-release bzip2 libdb4.8-dev gdb python help2man python-sphinx

autoconf/squeeze uptodate 2.67-2
blt-dev/squeeze uptodate 2.4z-4.2
bzip2/squeeze uptodate 1.0.5-6
debhelper/squeeze-backports uptodate 8.9.13~bpo60+1
gdb/squeeze uptodate 7.0.1-2+b1
help2man/squeeze uptodate 1.38.2
libbluetooth-dev/squeeze uptodate 4.66-3
libbz2-dev/squeeze uptodate 1.0.5-6
libdb4.8-dev/squeeze uptodate 4.8.30-2
libexpat1-dev/squeeze uptodate 2.0.1-7
libffi-dev/squeeze uptodate 3.0.9-3
libgpm2/squeeze uptodate 1.20.4-3.3
libncursesw5-dev/squeeze uptodate 5.7+20100313-5
libreadline-dev/squeeze uptodate 6.1-3
libsqlite3-dev/squeeze uptodate 3.7.3-1
libssl-dev/squeeze uptodate 0.9.8o-4squeeze5
libtinfo-dev not installed
locales/squeeze uptodate 2.11.2-10
lsb-release/squeeze uptodate 3.2-23.2squeeze1
mime-support/squeeze uptodate 3.48-1
netbase/squeeze uptodate 4.45
python/squeeze uptodate 2.6.6-3+squeeze6
python-sphinx/squeeze-backports uptodate 1.0.8+dfsg-2~bpo60+1
quilt/squeeze uptodate 0.48-7
sharutils/squeeze uptodate 1:4.9-1
tk8.5-dev/squeeze uptodate 8.5.8-1
zlib1g-dev/squeeze uptodate 1:220.127.116.11.dfsg-3

We see that everything except libtinfo-dev is available in squeeze. I do have the squeeze backport versions of debhelper and python-sphinx, but both of these are also available for debian squeeze in versions satisfying the build requirements.
Observe also that I have libncurses5-dev installed
apt-show-versions libncurses5-dev

libncurses5-dev/squeeze uptodate 5.7+20100313-5

Both of these packages correspond to the source package curses 5.7+20100313-5. Observe that libtinfo-dev in fact replaces libncurses5-dev.
apt-cache show libtinfo-dev

Package: libtinfo-dev
Source: ncurses
Version: 5.9-4
Installed-Size: 279
Maintainer: Craig Small <email@example.com>
Architecture: i386
Replaces: libncurses5-dev (<< 5.9-3)
Depends: libtinfo5 (= 5.9-4)

One would not expect python 2.7 to develop on such a specific version of curses, and in fact it doesn't. However, if you try to build the packages without satisfying the dependency you get
debuild -uc -us

dpkg-checkbuilddeps: Unmet build dependencies: libtinfo-dev
dpkg-checkbuilddeps: Build conflicts: libncurses5-dev
debuild: fatal error at line 1289:
You do not appear to have all build dependencies properly met.
You can use mk-build-deps to generate a dummy package which
Depends on all the required packages, or you can install them
manually using dpkg or apt using the error messages just above
this message.

So, it is necessary to edit debian/control. Note that you also need to similarly edit the file debian/control.in, otherwise the control
file will be incorrectly regenerated from control.in. The simplest thing to do is just remove libncurses5-dev
from the Build-Conflicts line and libtinfo-dev from the Build-Depends line, and then run debuild -uc -us
again. If you are going to have this package installed alongside the standard default Python 2.6 packages on Debian squeeze, you
also need to remove the two lines
Conflicts: python-profiler (<= 2.7.1-2)
Replaces: python-profiler (<= 2.7.1-2)

Those lines are there because 2.7 includes the python-profiler functionality.
If 2.7 is the default python, then python-profiler is no longer necessary.
However, if one is installing 2.7 as a non-default Python, that reasoning does not
apply, and python-profiler is still needed by 2.6.
This should build successfully, and result in the following list of binary packages.
ls -lah *.deb

-rw-r--r-- 1 faheem staff 289K Jan 12 02:33 idle-python2.7_2.7.2-8_all.deb
-rw-r--r-- 1 faheem staff 1.1M Jan 12 02:34 libpython2.7_2.7.2-8_i386.deb
-rw-r--r-- 1 faheem staff 2.5M Jan 12 02:34 python2.7_2.7.2-8_i386.deb
-rw-r--r-- 1 faheem staff  12M Jan 12 02:34 python2.7-dbg_2.7.2-8_i386.deb
-rw-r--r-- 1 faheem staff 4.9M Jan 12 02:34 python2.7-dev_2.7.2-8_i386.deb
-rw-r--r-- 1 faheem staff 6.0M Jan 12 02:33 python2.7-doc_2.7.2-8_all.deb
-rw-r--r-- 1 faheem staff 692K Jan 12 02:33 python2.7-examples_2.7.2-8_all.deb
-rw-r--r-- 1 faheem staff 1.7M Jan 12 02:34 python2.7-minimal_2.7.2-8_i386.deb

Finally, one can install the binary packages with
dpkg -i python2.7-minimal_2.7.2-8_i386.deb python2.7_2.7.2-8_i386.deb python2.7-dev_2.7.2-8_i386.deb libpython2.7_2.7.2-8_i386.deb

Sometimes dpkg can be a little difficult about satisfying dependencies when they are all installed at once, so you might have to run apt-get -f install afterwards if you get dependency errors, or alternatively install the packages in smaller groups.
Comment: Have you packaged this python-2.7-squeeze port?
Comment: @qMax: I did build a package based on these comments, yes. But I haven't put it anywhere public.
Comment: If 2.7.1-8 would suffice, then it's easier. Get it from "deb-src [...snapshot.debian.org...](http://snapshot.debian.org/archive/debian/20110520T212730Z/) testing main", apt-get build-dep python2.6, apt-get install libexpat1 libexpat-dev. And [pbuild](https://wiki.ubuntu.com/PbuilderHowto) it for squeeze as is.
Answer: Well if the only thing you need is argparse (saw that in one of your comments!) you could just do :
pip install argparse

This is not exactly an answer to the exact question :-) , but indeed if you are only missing a few feature, many 2.7 features actually come from independent projects and/or some compatibility packages can be found, eg:

argparse
Which implementation of OrderedDict should be used in python2.6? : OrderedDict on pypi
you should be able to replace memoryview with buffer

The list of 2.7 novelties is admittedly longer, but most of the other new features are probably not a big miss, and in exchange you do not mess around with multiple python installations on your box. Otherwise go with pythonbrew :-)
Answer: ubuntu 12.04
Install dependencies:
$ sudo apt-get install python-software-properties

Add the repo:
$ sudo add-apt-repository ppa:fkrull/deadsnakes

Update the repo index:
$ sudo apt-get update

Install Python 3.3:
$ sudo apt-get install python3.3

ubuntu 12.04 > more
Installing the dependencies:
$ sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev

Download and compile python:
$ wget http://python.org/ftp/python/3.3.0/Python-3.3.0.tar.bz2

$ tar jxf ./Python-3.3.0.tar.bz2

$ cd ./Python-3.3.0

$ ./configure --prefix=/opt/python3.3

$ make && sudo make install

Some nice touches to install a py command by creating a symlink:
$ mkdir ~/bin
$ ln -s /opt/python3.3/bin/python ~/bin/py

Answer: Just download Python 2.7 from http://www.python.org/download/releases/2.7.1/ and build it.
Comment: But use "make altinstall" instead of "make install".  "make install" will configure 2.7 to be the default version and you don't want that. "make altinstall" will leave the system Python alone and you'll just need to use "python2.7" to invoke it.
Comment: thanks. I got that part, but my question is more about how to switch back and forth between the two versions. With ruby I use RVM to manage multiple Ruby versions. Is there an equivalent in Python, or it not necessary?
Comment: Hmm. You can't "just build it". You'll need the build dependencies. Try "aptitude build-dep python2.7" or if that doesn't work, "aptitude build-dep python2.6" before trying to build from source. If you don't, you'll be missing a lot of important libraries.
Comment: Yes, make altinstall is the way to go.
Answer: Another option is to install ActivePython if you do not want to compile things yourself. It includes a binary package manager as well.
Answer: You can use virtualenv to create distinct Python environments. Just being newsy, but what does Python 2.7 have that you need?
Comment: I want to work with argparse. I'm python newsy, but not dev newsy ;)
Comment: flags on regular expressions!
Comment: Flags were around before 2.7, AFAIK.
Comment: To create a new virtualenv you need to have a python installed on your system. If you have only 2.6 installed, you can't create a virtualenv with python 2.7 !
Comment: @PawelRoman no, but the OP says they've been advised not to make 2.7 their default Python. Can still install it without making it the default.

Python 2.7 on Ubuntu


If $A \subseteq \mathbb{R}$ satisfies $m^\ast(A) = 0$, then there exist $B, C ∈ \mathcal{B}(\mathbb{R})$ such that $A = B \setminus C$?

Question: Is this a true claim or false? Recall that $m$ is Lebesgue measure and $m^\ast$ is Lebesgue outer measure. Also, $\mathcal{B}(\mathbb{R})$ in this case represents the Borel $\sigma$-algebra on $\mathbb{R}$.
I know that since $m^\ast(A) = 0$, then it can be shown that $A$ is Lebesgue measurable and hence $m(A) = 0$. I also know that since $B,C$ are Borel measurable, then they are Lebesgue measurable. My current strategy is to find a $B$ and $C$ that are Borel measurable and hence Lebesgue measurable such that $A = B \setminus C$ since $A$ is Lebesgue measurable. I'm not sure how to go about this.
Perhaps the claim isn't true?
Thanks for any help.
Comment: If $B, C$ are in the Borel $\sigma-$algebra then so is $B \setminus C$. So it boils down to whether you think every measure zero set is Borel.
Answer: As the comment suggests, for all Borel sets $B,C$, $B \setminus C$ is a Borel set.
Since there exists a non Borel Lebesgue measure zero set $A$, $A$ can't be a Borel set, so the claim is not true.
Comment: Perfect. Do we have a clear/simple example of a set $A$ with $m^\ast(A) = 0$ such that $A$ is Lebesgue measurable but not Borel measurable? Or only that we can guarantee the existence of one via the link you gave? Thanks.
Comment: @Darkdub, I can't think of any example simpler than the pre-image of a non-measurable subset of a Cantor set under $x \mapsto x + \phi(x)$, where $\phi$ is the Cantor Lebesgue function.  The simplicity of this example can be subjective.  When I first heard that in a tutorial, I was lost.  In fact, I've enhanced my memory of this through answering your question.


Basis of column space equivalence to transpose row space?

Question: If I find a basis for the column space of A, will that basis also be a basis for the column space of col(A transpose) ?
Answer: This is not true in general. First, if $A$ is not a square matrix then the column space and the row space live in vector spaces of different dimension. But even if it is a square matrix, then this claim is not true. For example
$$\left(\begin{array}{cc}
0 & 1\\
0 & 0
\end{array}\right)$$
has column space spaned by $\left(\begin{array}{c}
1\\
0
\end{array}\right)$ while $A^T$ has column space spanned by $\left(\begin{array}{c}
0\\
1
\end{array}\right)$.
While these spaces are not the same, they do have the same dimension, and this is always true.


Laravel - accessing relationship Models with AngularJS

Question: I am trying to create a single page app with AngularJS as my frontend and Laravel as my backend. I've run into a problem when trying to create a table that needs to access a relationship to another Model.
For this example, let's say I have a table that displays products. Every product would also have a brand.
With Laravel's blade syntax, I would solve this by using:

    Name
    Brand

  @foreach($products as $product)

    {{ $product->name }}
    {{ $product->brand->name }}

  @endforeach

With Angular, I was hoping I could do this:

    Name
    Brand Id

      @{{ product.name }}
      @{{ product.brand.name }}

Unfortunately, @{{ product.brand.name }} will not work and there doesn't appear to be an easy way to access parent relationships.
FYI, my controller looks like this:
app.controller('CtrlProducts', function($scope, $http){

  $scope.products = [];

  $http.get('/api/products').
    success(function(data, status, headers, config) {
      angular.forEach(data, function(product){
        $scope.products.push(product);
      });
    }).
    error(function(data, status, headers, config) {
      console.log(data);
    });
});

The only solution that I can think of is to make a separate api call to the Brand model and store the data into a map object. Then I could call: @{{ brandMap.get(product.brand_id) }}
Does anyone know of a simpler solution? Seems like it would be a common problem.
Thanks.
Answer: When fetching the product in your Laravel backend don't just use
Product::find($id);

but instead
Product::with('brand')->find($id);

There you go :) Corresponding docs section: http://laravel.com/docs/4.2/eloquent#eager-loading
Comment: I would, but need 15 reputation. Give me an upvote and I might be able to! ;)


Why don't we use the term "scale signature", rather than "key signature"?

Question: This would avoid the confusion to some, of saying that the key/mode of A dorian has a key signature of G. I'm all for making things clearer for people learning music. If a piece is in D dorian, I always put "D dorian" above the key signature of C. This makes it clear what mode/key the piece is really in.
I've read your replies, thanks for the comments and answers. I realised I was being provocative in suggesting a name change to a term that is firmly entrenched in our culture, and also calling a mode a key . But I was hoping to find some way of creating a disconnect between "key Signature" and  the tonal centre of a piece of music.
If the key signature is misleading, it helps if the tonal centre or mode is notated. Recently, I was given a simple 17th century Playford dance piece with a key signature of G. But the use of C#, and the chord structure, made it clear it was in the key of D major, as annotated by the person giving me the music. However, if I was creating a walking bass line around a diminished chord in jazz, it wouldn't help annotating it as a super locrian mode. I just have to know that half-whole tone intervals are used.
The discussion Key signature for writing in modes other than major and minor confirms my belief that the key signature just tells us the notes being commonly used, and any mode/tonal centre should be annotated. And sometimes using the "wrong" key signature, with more accidentals, helps people understand where the tonal centre may lie. E.g, using the key signature of F for a piece in D dorian.
This extract from the discussion quoted just above, sums it up nicely for me:
'The term "key signature" used in English does not translate exactly the meaning of what it is. In all other languagues, the literal translation would be "clef armature". So a clef armature is not meant to represent a musical key, but to simplify the process of reading music.' Thanks Flávio.
Answer: Let's take a step back and look at what a key is first. A key is a very specific concept in music theory. The key tells you what the tonic of a pieces is and the general type of Harmony to expect. A key will never indicated what scales to use which especially in a minor key could look vastly different from the key signature assigned to the key.
Since tonal harmony focuses on major and minor, trying to indicate modes with a key signature is always difficult. Most people just use if the mode is major or minor to determine what key signature they should use. For D Dorian, since it is a minor mode you could use the key signature for D minor to indicate it. Not a perfect fit, but it still preserves the indication on the tonic.
Comment: That still doesn't seem clear. An example would help. In a piece in E minor, is the key "E" or "E minor" or "G" or something else, and is the key signature "E minor", "G major" or "one sharp" or something else?
Comment: @Dom But given your answer leans heavily on "what is a key", (and given the asker's confusion with respect to key vs. scale vs. mode) it's probably worth attempting to clear up confusion on what, exactly, a key is. - You don't necessarily need to repeat details here, but I'd suggest picking one of the existing answers on this site which makes the point you want to make in the context of this answer, and then link to them.
Comment: What is a *key* in the first paragraph? Are you explaining what the key signature is, or are you defining the word *key*? In either case, the connection between key and key signature is not very clear by reading the first paragraph.
Comment: @JiK I cleaned it up a bit hopefully. Key and key signature are related topics since a key signature points to a key so explaining what keys are was needed at least for the question in the title.
Comment: Or maybe a better example would be a piece in another mode. The reason I'm saying this is that the question talks about "D dorian" as a key, but a comment says that D dorian is not a key. This answer starts by "let's look at what a key is first" but doesn't actually give enough information to answer that question.
Comment: @JiK From this answer "Since tonal harmony focuses on major and minor, trying to indicate modes with a key signature is always difficult.". I'd rather not turn this into a key vs mode answer since that's not what's asked and there are already several answers dedicated to that on the site.
Answer: A scale is a set of notes. That may be a major scale, any one of several minors, and possibly modes.
A key signature merely gives which notes in a piece are likely to be included in the following piece. The 'key signature* of 3# gives us a clue that the piece could be in A major, or maybe F#m. If it is indeed in F#m, then there are often several note changes that need to be made along the way, as harmonic minor has a slightly different set of notes in its scale from melodic (including possible natural minor).
So, even when the 'key sig.' is 3#, it's often not reflecting what's likely to be going on. We have to look for clues - the last note, is it A or F#? Is there a change in what the leading note's called? What harmonies are most prevalent?
That's the same with modes, the method you describe being my preferred, although if the 'key sig.' was 3#, I'd expect a B at the end, and a minor tonality to the piece if it was in B Dorian.
So, even with a change of name to 'scale signature', I don't see how that would help a lot. At least one composer, Bartok, I think, used something like Bb and F# in the 'key sig.' to indicate G minor - which actually makes some sense, however, it obviously didn't catch on - otherwise we'd be using it now!
Comment: Bartok often writes stuff on the edge of not being in any fixed mode; hence the wacky key signatures.
Comment: @CarlWitthoft - fair comment, but actually, with a key sig. of Bb and F#, it gets pretty close to being more accurate than Bb and Eb. Maybe he included Eb as well, not sure!
Answer: The key signature only tells you the number of accidentals used for the basic tonality.
From that starting point we can see that we don't know the tonic merely from a key signature, therefore we don't know what key/mode/scale will be used.
For example, if the key signature is one sharp. We could have a key of G major... or it could be E minor. Also, it could indicate a number of modes: C lydian, A dorian, D mixolydian, etc.
You must look at the score to really know what the tonic and mode are. Typically you can tell that by looking at the beginning and ending of the piece where traditionally the music starts and (especially) ends on the tonic.
You could think of the key/mode as an indicator of a scale. But that might be misleading when there are chromatic inflections of a basic diatonic scale such as chromatic passing tones or the raised ^6 or ^7 degrees in a minor key.

Just an historical aside: the modern key signature for minor keys indicates a "lowering" of the ^3, ^6, and ^7 scale degrees. So Eb, Ab, and Bb for C minor. But in Bach's time the key signature lowered only the ^3 and ^7. So back then Ed and Bb were the key signature for C minor. If we are looking for a scale, it sort of looks like a dorian mode signature, but that would be wrong. The music would be minor key using natural, harmonic and melodic minor scales.

Why don’t we use the term “scale signature”, rather than “key signature”?


Using Boosting tree to generate feature in sklearn

Question: I am referring to this link to Feature Transformation using tree ensembles for the context.
Specifically for below part of code, in the sample of the link, the method of (1) using Boosting tree to generate feature, then using LR to train, outperforms (2) using Boosting tree itself. Questions,

Wondering if it is true in general case using Boosting tree to generate feature (and using another classifier to classify) is better than using Boosting tree to do classification itself?
And also wondering why using Boosting tree to generate feature, then using LR to train, outperforms using Boosting tree itself?
grd = GradientBoostingClassifier(n_estimators=n_estimator)
grd_enc = OneHotEncoder()
grd_lm = LogisticRegression()
grd.fit(X_train, y_train)
grd_enc.fit(grd.apply(X_train)[:, :, 0])
grd_lm.fit(grd_enc.transform(grd.apply(X_train_lr)[:, :, 0]), y_train_lr)

Answer: The better performance of GBT+LR in the mentioned example is just because larger training set than GBT. Please note the GBT use X_train for training, while GBT+LR use X_train and X_train_lr. I prepared a new classificator GBT-ext, that is learned on the full training set, same as the GBT+LR.
grd_ext = GradientBoostingClassifier(n_estimators=n_estimator)
grd_ext.fit(np.concatenate([X_train, X_train_lr]), np.concatenate([y_train,
y_train_lr]))

y_pred_grd_ext = grd_ext.predict_proba(X_test)[:, 1]
fpr_grd_ext, tpr_grd_ext, _ = roc_curve(y_test, y_pred_grd_ext)

Results of the GBT-EXT are almost the same as the GBT+LR. See the picture below:

I think the result above answers both of your questions.


How to get parent URL in JS without using document.referrer

Question: I need to get the parent url which redirect to current page using JS, I find document.referrer can achieve, but our company has some security rules said can't trust that the referrer header is safe - it can be spoofed, omitted, or have an unexpected format.
I am asking are there any other way to achieve this? Thanks!
Answer: The other way I know of is looking into the window object
<code>window.location.origin
</code>


D7 Unique page/profile per user

Question: I am working a lot with views and panels to figure this out but i cant.
When user register account i want for him to be able to make his own profile visible to everyone.
Profile is 1 page user can create with custom content type (maybe there is something better to use?) with info from taxonomy vocabulary, random text, a gallery and a calendar.
Since there is lot of info to write in i want to separate this in few steps.
So i would like to divide page in few regions that look same for all users. Gallery on left side, taxonomy terms and random text in middle, calendar on right side or in block. Each region editable by user who made it. All info on that specific page must be only from user that created it (only userA pictures, userA calendar, userA random text on. All on 1 page).
I worked a lot with panels and views but i have no idea how to make all of this in a way that all info created by 1 user is on 1 page, viewable by everyone on that page.
I managed to use views to collect info from all users in 1 field/block/page so i know some basics. Also used panel to divide for example /home in more regions to.
Cheers!
Comment: Does the solution have to specifically use Panels?
Answer: This should really be pretty simple if you have created the Views properly.
You need to make the views select only the content that the user provided through an argument, fx uid = 5 would should show content user with uid 5 created.
Then it's just a matter of creating a panel page that has the uid in the url, fx user/[uid]/profile and pass the uid to the views when you insert them on the page, which then will display the correct content.
Comment: Not sure if i understand this correctly so ill try to elaborate.

I should make custom content that is panel, which when users makes content automaticly creates page and uses views to know what and how to display ?
Comment: @BigBrother2010: No you make a panel page which will display whatever content the user has created you want to display, gallery,calendar etc. You use views to display this content by using the uid of the user as an argument.

D7 Unique page/profile per user


Define advanced criteria for join tables in smartclient grid component for Openbravo ERP

Question: I'm newbie in a OpenBravo ERP system, so I'm sorry if I posted an obvious question.
I have created a custom MDI view in Openbravo ERP, added some input field for filtering product's name in Smarclient's listgrid which contains Orders. I have created a Order datasource and bind it to the Smartclient grid. What I want to achieve is to filter a Order list in the grid by product name which is added in the input text field. I tried with several approaches but without success.
So I came to question is it possible to add join table in AdvancedCriteria in the grid's fetchData function?
Here is a snippet of my code:
<code>isc.ELB_MainView.addProperties({
  form: null,
   grid: null,
   initWidget: function () {
    this.grid = isc.OBGrid.create({
     setDataSource: function (ds, fields) {
     var selectedFields = [],
     fs = OB.Constants.FIELDSEPARATOR,
     ident = OB.Constants.IDENTIFIER,
     fieldNames = ['documentNo', 'documentStatus', 'orderDate', 'accountingDate',        'businessPartner'+fs+ident, 'currency'+fs+ident],
     i, j;
     for(i = 0; i < fieldNames.length; i++) {
        for(j in ds.fields) {
           if(ds.fields.hasOwnProperty(j) && j === fieldNames[i]) {
              selectedFields.push(ds.fields[j]);
           }
        }
     }
       this.Super('setDataSource', [ds, selectedFields]);
     this.fetchData();
  }
  });
  this.form = isc.DynamicForm.create({
   fields: [{name : "productName",
          title: "Product Name",
          type : "text",
          width: '100%',
          change: function(form, item, value, oldValue){
             form.main.grid.invalidateCache();
             form.main.grid.fetchData({
                _constructor: 'AdvancedCriteria',
                operator: 'and',
                criteria: {
                   'fieldName': 'orderLineList.product.name',
                   'operator': 'equals',
                   'value': value
                }
            });
        this.Super('change', arguments);
   }}],
   main: this
  });

  OB.Datasource.get('Order', this.grid, null, true);

 this.addMember(this.form);
  this.addMember(this.grid);

 this.Super("initWidget", arguments);
}

});
</code>
Tnx in advance.
Answer: Similar question is posted on SmartClient Forum about Joining tables for listgrid datasource.
Here is my solution that will definitely solve your problem:
Create a view that is created by joining tables required for grid and use it as data source


What does a marking of Trio. mean on a score?

Question: In this version of Mozart's German Dances, the third section of each dance has "Trio." engraved above the staff.  What does this indicate?
Answer: It usually means it is the Trio section from a Minuet and Trio form. And, although the beginning of the score you link to is not marked "Minuet", it is in 3/4 and in the style of a Minuet.
Originally the Minuet was a kind of dance, with Minuet also describing the associated 3/4 dance music form. Later it became common to combine this form with a Trio section, creating a longer structure.
When this form first became common the Trio section would be literally that, a section scored for only three instruments, but the term continues to be used even where the instrumentation is for larger forces. However, even where the ensemble is larger, the Trio section usually has lighter orchestration and a simpler texture. This has particular relevance when one considers that the Minuet and Trio form was often used for the third movement of the classical four-movement symphony.
Comment: You get the same thing in military and brass band marches. The last section before the *DC* is called the trio, and it's often marked as such on the parts. In a march, the lighter orchestration you mention is usually achieved by giving the tune to the horns, with a much dancier, springier feel.


PHP Change SOAP NameSpace

Question: I am attempting to change the namespace as it needs to match the .NET web service namespace it is attempting to call however am unable to. How do I change the name space?
<code>class MSWCF extends SoapClient
{
    function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        /*
         * $request is a XML string representation of the SOAP request
         * that can e.g. be loaded into a DomDocument to make it modifiable.
         */

        $domRequest = new DOMDocument();
        $domRequest->loadXML($request);

        // modify XML using the DOM API, e.g. get the <s:Header>-tag
        // and add your custom headers
        $xp = new DOMXPath($domRequest);
        $xp->registerNamespace('SOAP-ENV', 'http://schemas.xmlsoap.org/soap/envelope/');
        // fails if no <s:Header> is found - error checking needed
        $envelope = $xp->query('/SOAP-ENV:Envelope')->item(0);

        // now add your custom header
        $header = $domRequest->createElement('SOAP-ENV:header');
        $security = $domRequest->createElement('o:Security');
        $usernameToken = $domRequest->createElement('o:UsernameToken');
        $usernameTokenuid = new DOMAttr('u:Id','uuid-4d9bf7e6-da00-4f72-8383-6037f12a0fb5-5');
        $username = $domRequest->createElement('o:Username','');
        $password = $domRequest->createElement('o:Password','');
        $passwordtype = new DOMAttr('Type','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText');
        $password->appendChild($passwordtype);
        $usernameToken->appendChild($username);
        $usernameToken->appendChild($password);
        $usernameToken->appendChild($usernameTokenuid);

    $timestamp = $domRequest->createElement('u:TimeStamp');
    $timestampuid = new DOMAttr('u:Id','_0');

    $interval = new DateInterval("PT5M");
    $dateCreated = new DateTime();
    $dateExpires = new DateTime();
    $dateExpires->add($interval);
    $created = $domRequest->createElement('u:Created', $dateCreated->format(DATE_ISO8601));
    $expires = $domRequest->createElement('u:Expires', $dateExpires->format(DATE_ISO8601));
    $timestamp->appendChild($timestampuid);
    $timestamp->appendChild($created);
    $timestamp->appendChild($expires);

    $security->appendChild($timestamp);
    $security->appendChild($usernameToken);

    $securitymust = new DOMAttr('SOAP-ENV:mustUnderstand','1');
    $securityxml= new DOMAttr('xmlns:o','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd');
    $security->appendChild($securitymust);
    $security->appendChild($securityxml);

        $header->appendChild($security);
    $envelope->appendChild($header);

        $request = $domRequest->saveXML();

    echo $request;

        return parent::__doRequest($request, $location, $action, $version, $one_way = 0);
    }
}
</code>
Answer: If your SOAP message actually uses the namespace, you can use SoapVar() to specify the name space of a particular variable.  When the SoapClient builds the message, it should include the namespace.

PHP Change SOAP NameSpace


Filter a view result by matching a view field to a URL term

Question: I have a content type called "Post" which contains two fields:
1) title
2) username
I created a View which creates a block that gathers all Posts. The block will reside on a user's account page, wherein the URL will always be:
www.mysite.com/user/username
How can I filter that block to only show the results where the username field matches the second term in the URL?
Thanks!
Answer: Use contextual filter in views and set raw value as second argument from the url (here second argument will be username).


Creating multiple columns in data table with a for loop

Question: My data table looks like:
head(data)
    Date         AI   AGI      ADI   ASI   ARI   ERI   NVRI  SRI   FRI  IRI
1: 1991-09-06    NA 2094.19    NA    NA    NA    NA    NA    NA    NA    NA
2: 1991-09-13    NA 2204.94    NA    NA    NA    NA    NA    NA    NA    NA
3: 1991-09-20    NA 2339.10    NA    NA    NA    NA    NA    NA    NA    NA
4: 1991-09-27    NA 2387.81    NA    NA    NA    NA    NA    NA    NA    NA
5: 1991-10-04    NA 2459.94    NA    NA    NA    NA    NA    NA    NA    NA
6: 1991-10-11    NA 2571.07    NA    NA    NA    NA    NA    NA    NA    NA

Don't worry about the NAs. What I want to do is make a "percentage change" column for each of the columns apart from date.
What I've done so far is:
names_no_date <- unique(names(data))[!unique(names(data)) %in% "Date"]

for (i in names_no_date){
      data_ch <- data[, paste0(i, "ch") := i/shift(i, n = 1, type = "lag")-1]}

I get the error:
Error in i/shift(i, n = 1, type = "lag") :
  non-numeric argument to binary operator

I'm wondering how I get around this error?
Comment: please be more clear, what do you mean by "percentage change" -you mean a growth function?
Comment: You 'get around it' by only passing 'numerics' into a 'binary operator'. Your `i / shift(i, ...)` is expecting numeric values as both the numerator & denominator. Maybe you need to worry about the `NA`s? And make sure you're not `lag`ging to a non-existent row.
Comment: If you're using data.table, use data.table syntax. To make a new data.table, `dt[, lapply(.SD, function(i){i / shift(i)}), .SDcols = -1]`. To add on to the existing one; `dt[, paste0(names(dt)[-1], 'ch') := lapply(.SD, function(i){i / shift(i)}), .SDcols = -1]`. And if you must use `for` loops, preallocate an object of the appropriate size.
Answer: i is a string, so you are trying to divide a string in i/shift(i, n = 1, type = "lag"):
> "AI"/NA
Error in "AI"/NA : non-numeric argument to binary operator

Instead, do
for (i in names_no_date){
      data[, paste0(i, "ch") := get(i)/shift(get(i), n = 1, type = "lag")-1]
}

Also see Referring to data.table columns by names saved in variables.

Edit:  @Frank writes in the comments that a more concise way to produce OP's output is
data[, paste0(names_no_date, "_pch") := .SD/shift(.SD) - 1, .SDcols=names_no_date]

Comment: You can also do it in one step, I guess: `data[, paste0(names_no_date, "_pch") := .SD/shift(.SD) - 1, .SDcols=names_no_date]`
Comment: ...that's how you `get` around this error `*ducks*`
Comment: Thanks, that's excellent! I read the ?get help file, but i couldn't understand what it does. Do you mind explaining what get() does?
Comment: `get("x")` returns the object with the name "x" in the environment where `get` was called. For example, try `x <- rnorm(5); get("x")`.
Comment: Hi @Frank, I'm curious, what does the .SD mean?
Comment: Sure, it refers to the Subset of Data used in `j` of `DT[i, j]`. You can find details like this in the introductory materials for the package: https://github.com/Rdatatable/data.table/wiki/Getting-started @Gin_Salmon


Onclick no android não funcionando

Question: Buenas pessoal, tudo bem? Estou usando um RecyclerView para popular minha lista no Android e para tal tenho um adapter e um view holder.
Segue código fonte do Adapter com o ViewHolder
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder> {
private OnItemClicked onClick;

public interface OnItemClicked {
    void onItemClick(int position);
}

private final List<Movie> moviesList;
private final Context context;

public MoviesAdapter(List<Movie> moviesList, Context context) {
    this.moviesList = moviesList;
    this.context = context;
}

@Override
public MoviesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    int layoutIdForItem = R.layout.filme_item;
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(layoutIdForItem, parent, false);
    return new MoviesViewHolder(view);
}

@Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
    Movie movie = moviesList.get(position);
    String imagemUri = movie.getPosterPath();
    Picasso
            .with(context)
            .load(imagemUri)
            .into(holder.mPosterMovieImageView);
    holder.mPosterMovieImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onClick.onItemClick(position);
        }
    });

}

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

public class MoviesViewHolder extends RecyclerView.ViewHolder {

    public final ImageView mPosterMovieImageView;

    public MoviesViewHolder(View view) {
        super(view);
        mPosterMovieImageView = view.findViewById(R.id.iv_movies_poster);
    }

}

public void setOnClick(OnItemClicked onClick) {
    this.onClick = onClick;
}

}
Meu app carrega toda a lista de filmes usando Retrofit porem ao clicar em um filme, deveria ir para outra activity para exibir detalhes. Porem esse OnClick não está funcionando.
Segue o Código de minha MainActivity
 private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private MoviesAdapter mMoviesAdapter;
private List<Movie> movies = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initViews();
}

private void initViews() {

    mRecyclerView = (RecyclerView) findViewById(R.id.rv_lista_filmes);
    GridLayoutManager gridManager = new GridLayoutManager(MainActivity.this, 2);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(gridManager);
    loadPopularMovies();
}

private void loadPopularMovies() {

    Call<MoviesDTO> call = new RetrofitStarter().getMovieService().retrievePopularMovies("api-key");

    call.enqueue(new Callback<MoviesDTO>() {

        @Override
        public void onResponse(Call<MoviesDTO> call, Response<MoviesDTO> response) {
            MoviesDTO moviesDTO = response.body();
            movies = new ArrayList<>();
            for (Movie movie : moviesDTO.getMovies()) {
                movies.add(movie);
            }
            initAdapter(movies);

        }

        @Override
        public void onFailure(Call<MoviesDTO> call, Throwable t) {
            Log.e("ERROR", "error loading popular movies: " + t.getMessage());

        }
    });

}

private void initAdapter(List<Movie> movies) {
    mMoviesAdapter = new MoviesAdapter(movies, MainActivity.this);
    mRecyclerView.setAdapter(mMoviesAdapter);
}

private void loadTopRatedMovies() {
    Call<MoviesDTO> call = new RetrofitStarter().getMovieService().retriveTopRatedMovies("api-key");

    call.enqueue(new Callback<MoviesDTO>() {
        @Override
        public void onResponse(Call<MoviesDTO> call, Response<MoviesDTO> response) {
            MoviesDTO moviesDTO = response.body();
            movies = new ArrayList<>();
            for (Movie movie : moviesDTO.getMovies()) {
                movies.add(movie);
            }
        }

        @Override
        public void onFailure(Call<MoviesDTO> call, Throwable t) {
            Log.e("ERROR", "error loading top rated movies: " + t.getMessage());
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    URL url = null;
    int id = item.getItemId();
    switch (id) {
        case R.id.mi_popular:
            loadPopularMovies();
            break;
        case R.id.mi_melhor_avaliado:
            loadTopRatedMovies();
            break;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onItemClick(int position) {
    Movie movie = movies.get(position);
    Intent intentSelectedMovieDetail = new Intent(this, MovieDetailActivity.class);
    intentSelectedMovieDetail.putExtra("selectedMovie", movie);
    startActivity(intentSelectedMovieDetail);
}

Esse é o stack trace que gera quando tento clicar em algum item
12-15 08:02:11.667 7551-7551/br.com.agilles.filmesfamosos E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: br.com.agilles.filmesfamosos, PID: 7551
                                                                        java.lang.NullPointerException: Attempt to invoke interface method 'void br.com.agilles.filmesfamosos.adapters.MoviesAdapter$OnItemClicked.onItemClick(int)' on a null object reference
                                                                            at br.com.agilles.filmesfamosos.adapters.MoviesAdapter$1.onClick(MoviesAdapter.java:58)
                                                                            at android.view.View.performClick(View.java:6294)
                                                                            at android.view.View$PerformClick.run(View.java:24770)
                                                                            at android.os.Handler.handleCallback(Handler.java:790)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                            at android.os.Looper.loop(Looper.java:164)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Comment: Acho que faltou você referênciar o click para sua Activity. Tente assim mMoviesAdapter.setOnClick(this);
Comment: realmente, era isso mesmo, errinho tonto que fez eu perder a manhã inteira kkkkk
Comment: Relacionado: [Qual é a abordagem certa para pegar o click/posição no RecyclerView?](https://pt.stackoverflow.com/q/159830/2541)
Comment: interessante esse link. Vou dar uma pesquisada se usei da maneira correta
Answer: Não foi atribuído o objecto que deve ser usado pelo adapter para tratar o onClick.
Julgo que é sua Activity que implementa a interface MoviesAdapter.OnItemClicked, se assim é, ela deve ser atribuída ao adapter através do método setOnClick():
private void initAdapter(List<Movie> movies) {
    mMoviesAdapter = new MoviesAdapter(movies, MainActivity.this);

    mMoviesAdapter.setOnClick(this);

    mRecyclerView.setAdapter(mMoviesAdapter);
}

Comment: PQP, que erro besta kkkkkkkkkkkk, tinha esquecido disso mesmo

Onclick no android não funcionando


Derivative $= 0$ at Extremum Necessary and sufficient?

Question: The condition that the derivative at the extremum of an uniformly differentiable function is zero.
is this necessary and sufficient or both?
Comment: Does considering $f(x) = x^3$ at $x=0$ answer one of your questions?
Comment: What does "uniformly differentiable" mean?
Comment: To sum up, its necessary, but not sufficient.
Comment: @NateEldredge ya thanks, it clearly did
Answer: Define $x^*$ to be a point where $f'(x^*)=0$.
Necessary
In order to show if $f'(x^*)=0$ is necessary for $x^*$ to be an extremum, we must show that:

If $f'(x^*) \ne 0$ then $x^*$ cannot be an extremum.

Intuitively, if $f'(x^*) \ne 0$ then it must be the case that either $f'(x^*) \gt 0$ or $f'(x^*) \lt 0$ which implies that the function $f(x)$ is either increasing or decreasing at $x^*$ respectively. Therefore, $x^*$ cannot be an extremum.
Sufficient
In order to show sufficiency we have to show that:

If $f'(x^*) = 0$ then $x^*$ must be an extremum.

Suppose that $f'(x^*) = 0$. If the point $x^*$ must be an extremum it must be the case that either:

$f(x)$ is decreasing to the left of $x^*$ and increasing to the right of $x^*$
<code>                              or
</code>
$f(x)$ is increasing to the left of $x^*$ and decreasing to the right of $x^*$

But, $f'(x^*)=0$ by itself cannot tell us anything about the behavior of $f(x)$ in a local neighborhood of $x^*$. Thus, $f'(x^*)=0$ is not a sufficient condition for $x^*$ to be an extremum.

Note that the above arguments are informal and rely on geometrical intuition. However, they can be formalized depending on how much rigor you wish for your proof.
The above arguments only indicate that the following:

$x^*$ may be a candidate for an extremum. You need additional tests (in particular the second derivative test) to check if it is in fact an extremum.
$x^*$ may not be a global extremum.
Comment: Even locally, a vanishing derivative isn't sufficient.  For example $x^3$ at the origin.  If you add the condition that the second derivative not vanish, then you have sufficiency.
Comment: @RileyE hmm, true. Let me fix my answer.


Create Module Control during installation of module in DNN

Question: I have finished developing my module for dotnetnuke, but I need to have my controls pages already added after the module is installed instead of adding all the control pages myself
Answer: Found my answer:
In the solution explorer, there is a file that is called the name of your module with the file extension of dnn. Ex: MyModule.dnn
Open that and look for the tag <moduleControl>. From there you can create your own control that will be added during the installation process.
Here is my example:
<moduleControl>
    <controlKey>GestionCategories</controlKey>
    <controlSrc>DesktopModules/DemandePosteEnLigne/GestionCategories.ascx</controlSrc>
    <supportsPartialRendering>False</supportsPartialRendering>
    <controlTitle>Gestion des Categories</controlTitle>
    <controlType>Edit</controlType>
    <iconFile />
    <helpUrl />
    <viewOrder>0</viewOrder>
    <supportsPopUps>True</supportsPopUps>
</moduleControl>

Answer: There is no event in dnn like OnModuleInstalled or something. But you can achieve what you want to do by creating page template/ portal template based on your requirements.
If you are willing to create 2-3 new pages, you can simply export those pages as template and then you can use dnn file manager to upload the page templates and then use those page templates to create pages. Good thing about this is, in future also, if you want to create similar pages, you can re-use those templates.
If you are willing to create entire portal's page hierarchy which includes more than 5 pages, you need to go for portal template. You can export portal as template by login to host account and go to Host > Portals (Site Management). You have to upload your portal template through FTP and then you have to create your new template by using that template.
Let me know if you need any other help.
Thanks
Comment: thanks, but creating a template isnt what I'm looking for... To create the template, I still need to preinstall the module and add the control pages manually after the installation
Comment: As I said, that is not possible through any inbuilt feature in dnn. You have to write some custom code to do so.


emacs - save current buffer list to a text file

Question: Quite often I need to get a simple text copy of my currently opened files. The reasons are usually:

I want to send the list to a colleague
I want to document whatever I am working on (usually in an org document)
I want to act on one of my currently opened files, on the shell. I need to copy-paste the pathname for that.

The fact is that the usual buffer-menu or list-buffers provide a convenient menu to navigate the opened buffers, but are very inconvenient to copy-paste to the the terminal the names of the opened files, or to perform any of the actions mentioned above. For example: I can not double-click in a line to select the full path-name, and I can not use the kill/yank emacs sequence to copy around the path-name.
Summary: I would like a way to export to a text file (or to a new buffer) the list of opened files, without other data; no file size, mode, or any other emacs metadata.
Is there a command for that? An extra package I can install?
EDIT
Adding solution by Trey Jackson, modified to provide some feedback of what has been done:
(defun copy-open-files ()
  "Add paths to all open files to kill ring"
  (interactive)
  (kill-new (mapconcat 'identity
                       (delq nil (mapcar 'buffer-file-name (buffer-list)))
                       "\n"))
  (message "List of files copied to kill ring"))

Answer: This command will do the job for you:
(defun copy-open-files ()
  "Add paths to all open files to kill ring"
  (interactive)
  (kill-new (mapconcat 'identity
                       (delq nil (mapcar 'buffer-file-name (buffer-list)))
                       "\n")))

Comment: This is it! I can easy paste the kill-ring wherever I am working, and from there to the shell if need be.
Answer: You can change the mode of your *Buffer List* buffer.  By default, it will be in mode Buffer Menu, but changing it to text-mode or fundamental-mode will remove all the special behavior allowing you to cut and paste from it just like a regular buffer.  The metadata can easily be chopped off with delete-rectangle.
Alternatively, you can access the buffer list programmatically with elisp:
(dolist (buffer (buffer-list))
  (when (buffer-file-name buffer)
    (insert (buffer-file-name buffer) "\n")))

Comment: Although that would be a workable solution, it means too many keystrokes to make it practical. I am using this really often.
Answer: You certainly should be able to copy and yank from the buffer list.
e.g. copy everything with C-xhM-w and then yank into a new buffer for editing.


Find $f(x)$ such that $\sum_{k=0}^{\infty}f^k\left(x\right)=\sum_{k=0}^{\infty}f^{\left(k\right)}\left(x\right)$

Question: I wonder how we can find all $f(x)$ that satisfies$$\sum_{k=0}^{\infty}f^k\left(x\right)=\sum_{k=0}^{\infty}f^{\left(k\right)}\left(x\right)\tag{1}$$Here $f^{(k)}(x)$ means the $k$th derivative of $f(x)$.
We could tell that this DE is not a linear differential equation, let alone has a finite order. For the LHS to converge, $|f(x)|<1$. So we could use geometric series to write this as $$\frac1{1-f(x)}=\sum_{k=0}^{\infty}f^{\left(k\right)}\left(x\right)$$Replacing $f(x)=y$ and integrating with respect to $y$, we get $$-\ln|1-y|=\frac{y^2}2+\int\sum_{k=1}^\infty y^{(k)}dy+C$$I was thinking of substituting the LHS of $(1)$ into the integrand, but that just gives $-\ln|1-y|=-\ln|1-y|$. How can we solve this differential equation? If we don't have a closed form, can we write the equation differently (not something obvious like adding and subtracting the same number), obtain asymptotics for $f(x)$, or find approximations?
Comment: Please do not use titles consisting only of math expressions; these are discouraged for technical reasons -- see [Guidelines for good use of $\rm\LaTeX$ in question titles](http://meta.math.stackexchange.com/a/9730).
Answer: Formally, we can reduce this to a first order separable ODE for $y$. Let $D = \frac{d}{dx}$, then our equation reads $$\sum_{k=0}^\infty y^k = \left(\sum_{k=0}^\infty D^k\right)y.$$ Again operating formally, we now sum both geometric series to obtain $$\frac{1}{1-y} = (I - D)^{-1}y,$$ where $(I-D)^{-1}$ denotes the inverse of the operator $I - D$ whose action on a function $f$ is $f - f'$. Left multiplying by $I-D$, we obtain $$(I-D)\left(\frac{1}{1-y}\right) = \frac{1}{1-y} - \frac{y'}{(1-y)^2} = y.$$ We can then rearrange into standard form to obtain $$y' = -y^3 + 2y^2 - 2y + 1.$$ Such an equation can be solved locally for most initial conditions and WolframAlpha gives some implicit equations for $y$, although it isn't clear which, if any, of these solutions satisfy the necessary conditions to justify the convergence of the original infinite series.
Answer: If that makes sense at all in all the limits, and the term-wise derivative is justified on both sides (which should follow in this special case from the general convergence), then you can subtract the derivative from the original equation to get
$$
\frac1{1-f(x)}-\frac{f'(x)}{(1-f(x))^2}=f(x)
$$
which is a separable first-order DE
$$
\frac{f'(x)}{(f(x)-1)(f(x)^2-f(x)+1)}=-1.
$$
This has a standard algorithm to get an implicit solution.
Comment: The sign in front of the $f'(x)$ should be negative.
Comment: Yes, in a difference there should be a minus sign.
Answer: Too long for a comment.
Starting from @whpowell96's answer, switching variables, the equation is
$$x'=\frac{1}{(1-y) \left(y^2-y+1\right)}$$ which gives
$$x+C=\frac{1}{\sqrt{3}}\tan ^{-1}\left(\frac{2 y-1}{\sqrt{3}}\right)+\frac{1}{2} \log \left(\frac{\left| y^2-y+1\right|
   }{(1-y)^2}\right)$$ which will be impossible to inverse.


Inserting a line of text at the beginning of an Access export

Question: I would like to export Access query results to a text file with some added string in the first line of exported file.
Specifically, I would like to combine a text string:
 *Abc def

with the Access query results (tab delimited):
DoCmd.TransferText acExportDelim, "Export_spec", "Export", "C:\export.txt", True, ""

and then save it as a text file.
The text string have to be in the first line of the text file, followed by access query results.
The results should looks like:
*Abc def
Header1 Header2 Header3 Header4 ...
Value1 Value2 Value3 Value4 ...
... ... ... ... ...

Answer: You will need to

export the data to a temporary file,
create a new text file,
write the string to the new text file, and then
append the data from the temporary file to the new file.

One way to accomplish that would be to use a FileSystemObject in code like this
Dim tempExportSpec as String
tempExportSpec = "C:\__tmp\tempexport.txt"
DoCmd.TransferText acExportDelim, "Export_spec", "Export", tempExportSpec, True, ""
Dim fso As New FileSystemObject
Dim finalFile As TextStream
Set finalFile = fso.CreateTextFile("C:\folder\export.txt")
finalFile.WriteLine "*Abc def"
Dim tempExport As TextStream
Set tempExport = fso.OpenTextFile(tempExportSpec, ForReading)
finalFile.Write tempExport.ReadAll
finalFile.Close
tempExport.Close
fso.DeleteFile tempExportSpec


Capturar valor de retorno da query Racket

Question: Olá, sou iniciante no racket. Gostaria de capturar o valor insert-id que retorna em um uma struct chama simple-result da query que executo. O retorno é o seguinte:
<code>(simple-result '((insert-id . 30) (affected-rows . 1)))
</code>
Gostaria de obter o valor 30 por exemplo.
Código da execução da query:
<code>(define save_pergunta
  (lambda (tf_pergunta)
  (define result_save_pergunta (
      query conn "INSERT INTO perguntas VALUES (null, $pergunta)" tf_pergunta))
  (print result_save_pergunta)
  (printf "\nPergunta Cadastrada!\n")))
</code>
Answer: Consegui realizar oque precisava com a função  dict-ref  passando a query e o identificador como parametros.
Ficando desta forma:
<code>(define save_pergunta
 (lambda (tf_pergunta)
  (define result_save_pergunta (
       dict-ref (
           query conn "INSERT INTO perguntas VALUES (null, $pergunta)" tf_pergunta) 'insert-id)
  (print result_save_pergunta)
  (printf "\nPergunta Cadastrada!\n")))
</code>


timeout a subprocess

Question: I realize this might be a duplicate of Using module 'subprocess' with timeout. If it is, I apologize, just wanted to clarify something.
I'm creating a subprocess, which I want to run for a certain amount of time, and if it doesn't complete within that time, I want it to throw an error. Would something along the lines of the following code work or do we have to use a signal like answered in the other question? Thanks in advance!:
def run(self):
    self.runTestCmd()
    self.waitTestComplete(self.timeout)

def runTestCmd(self):
    self.proc = subprocess.Popen("./configure", shell=True)

def waitTestComplete(self, timeout):
    st = time.time()
    while (time.time()-st) < timeout:
        if self.proc.poll() == 0:
            return True
        else:
            time.sleep(2)
    raise TestError("timed out waiting for test to complete")

Answer: It would, but it has a problem.  The process will continue on doing whatever it is you asked it to do even after you've given up on it.  You'll have to send the process a signal to kill it once you've given up on it if you really want it to stop.
Since you are spawning a new process (./configure which is presumably a configure script) that in turn creates a whole ton of sub-processes this is going to get a little more complex.
import os

def runTestCmd(self):
    self.proc = subprocess.Popen(["./configure"], shell=False,
                                 preexec_fn=os.setsid)

Then os.kill(-process.pid, signal.SIGKILL) should kill all the sub-processes.  Basically what you are doing is using the preexec_fn to cause your new subprocess to acquire it's own session group.  Then you are sending a signal to all processes in that session group.
Many processes that spawn subprocesses know that they need to clean up their subprocesses before they die.  So it behooves you to try being nice to them if you can.  Try os.signal(-process.pid, signal.SIGTERM) first, wait a second or two for the process to exit, then try SIGKILL.  Something like this:
import time, os, errno, signal

def waitTestComplete(self, timeout):
    st = time.time()
    while (time.time()-st) < timeout:
        if self.proc.poll() is not None:  # 0 just means successful exit
            # Only return True if process exited successfully,
            # otherwise return False.
            return self.proc.returncode == 0
        else:
            time.sleep(2)
    # The process may exit between the time we check and the
    # time we send the signal.
    try:
        os.kill(-self.proc.pid, signal.SIGTERM)
    except OSError, e:
        if e.errno != errno.ESRCH:
            # If it's not because the process no longer exists,
            # something weird is wrong.
            raise
    time.sleep(1)
    if self.proc.poll() is None: # Still hasn't exited.
        try:
            os.kill(-self.proc.pid, signal.SIGKILL)
        except OSError, e:
            if e.errno != errno.ESRCH:
                raise
    raise TestError("timed out waiting for test to complete")

As a side note, never, ever use shell=True unless you know for absolute certain that's what you want.  Seriously.  shell=True is downright dangerous and the source of many security issues and mysterious behavior.
Comment: @user388025 - That is indeed how you would go about doing it.  Except, it's configure, right?  That means it spawns a ton of sub-processes, and some of those may take awhile to die off.  In order to make that work you might have to do something lots more complicated so those processes end up with their own process group.
Comment: @user388025 - You mean `["make", "test"]`.  Never use `shell=True` unless you absolutely have to and know what you're on about.  And yes, that will also spawn lots of subprocesses, and I edited my answer to answer your question.  You might also want to try sending make the `SIGINTR` or `SIGTERM` signals instead of `SIGKILL` so it has a chance to try to clean up the subprocesses it spawns.
Comment: @user388025 - I made a mistake.  *sheepish grin*  I should've had `self.proc.poll() is not None`. instead.
Comment: Thanks for your reply :) I'm running python 2.5 though, which doesn't have pOpen.kill(), and was wondering how I could go about killing the subprocess. I tried http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kill-a-subprocess but that doesn't seem to work.
Comment: Oops, deleted my comment accidentally. I'm going to try what you just said, thanks for your time :)
Comment: @user388025 - I edited my answer to solve a number of other problems you might end up encountering and fix up your code to not think a test failure is the same as a timeout.
Comment: Omnifarious, what happens if configure exits after receiving the SIGTERM, but one or more of its children stubbornly remain behind?  If I'm not mistaken, poll() would return an exit code and you would never send the SIGKILL signal to those remaining processes.
Comment: @Omnifarious, it worked...thanks for the answer and the brilliant explanation :)
Comment: @Marius Gedminas: I believe you might be correct, and I'm not completely sure what to do about that.  I would have to research what happens to the process group once the process group leader exits.  Because if a new process becomes the group leader, and the process group acquires a new id (which I expect is the case) there's no real way to reference all of those processes anymore.  You'd have to capture a process tree or something before the leader exited, and that might change over time.
Comment: @Omnifatious, I'm a little confused as to how I can differentiate between a timeout error and a test error (how did you know I was going to run into this problem down the line? lol). In the code you've edited, (if self.proc.poll() is None: return self.proc.returncode == 0), doesn't checking if proc.poll() is None mean that the process is still running? If it's still running, how can proc.returncode be equal to 0, in the next line? Sorry if this is a stupid question!
Comment: Sorry. This is an old post, but can anyone tell me what the dash in there is for? `os.kill(-self.proc.pid, signal.SIGTERM)`

timeout a subprocess


Problemas ao executar classe em Java

Question: Quando vou invocar o método desta classe:
package newpackage;

import java.util.ArrayList;
import javax.swing.JOptionPane;

public class Operacoes {

    /*
     DESENVOLVIDO BY: "IIJM Team"
     */

    Cliente clientes;
    ArrayList<Cliente> cliente;

    public Operacoes() {
        cliente = new ArrayList<>();
    }

    int aux = 0;

    public void cadastroCliente() {
        aux++;
        clientes.setCodigo(aux); // O erro ocorre quando chega aqui!
        clientes.setNome(JOptionPane.showInputDialog((aux)
                + "º Cliente\nNome: "));
        clientes.setEmail(JOptionPane.showInputDialog("E-mail: "));

        cliente.add(clientes);

    }
 }

Aparece o seguinte problema:

Exception in thread "main" java.lang.NullPointerException

Classe do método main:
package newpackage;

import java.util.ArrayList;

public class Programa {

    public static void main(String[] args) {
       Operacoes op = new Operacoes();
            op.cadastroCliente(); // Ocorre um erro aqui também
    }
}

Comment: Cara, tenta editar tua questão colocando a saída completa do erro.
Comment: @bigown Obrigado por me lembrar, e obrigado por sempre está me ajudando! Forte abraço. Obs: tenho apenas 16 anos e quando crescer quero ser como você...
Comment: Informe qual a linha onde o erro ocorre (não só o número porque não temos como saber qual é o número aqui, mostre a linha)
Comment: Na classe Programa ocorre na linha 9, na classe Operacoes ocorre na linha 23;
Comment: Como o @bigown disse, nós não temos como saber qual é o número da linha, mostre a linha.
Comment: @bigown e Jéferson coloquei comentários nas linhas que o erro ocorre.
Comment: http://pt.stackoverflow.com/questions/49013/exception-in-thread-main-java-lang-nullpointerexception
Comment: @IgorAlisson [esta conta](http://pt.stackoverflow.com/users/21284/igor-gutemberg) também é sua? Se for, me avise, podemos fundir as duas se quiser.
Answer: A variável clientes não foi instanciada.
Tudo o que precisa fazer é instanciá-la (clientes = new Cliente()).
public void cadastroCliente() {
    clientes = new Cliente(); //adicione esta linha
    aux++;
    clientes.setCodigo(aux); // O erro ocorre quando chega aqui!
    clientes.setNome(JOptionPane.showInputDialog((aux) + "º Cliente\nNome: "));
    clientes.setEmail(JOptionPane.showInputDialog("E-mail: "));

    cliente.add(clientes);
}

Answer: Você precisa instanciar a classe Cliente na variável clientes antes de usá-la. Mas eu melhoria este código um pouco mais, assim:
package newpackage;

import java.util.ArrayList;
import javax.swing.JOptionPane;

public class Operacoes {
    ArrayList<Cliente> clientes;

    public Operacoes() {
        cliente = new ArrayList<Cliente>(); //note que mudei os nomes para ficar menos confuso
    }

    public void cadastroCliente() {
        Cliente cliente = new Cliente();
        int aux = clientes.size() + 1; //pega a quantidade de elementos atual e incrementa
        cliente.setCodigo(aux);
        cliente.setNome(JOptionPane.showInputDialog((aux)
                + "º Cliente\nNome: "));
        cliente.setEmail(JOptionPane.showInputDialog("E-mail: "));

        clientes.add(cliente);
    }
}

Coloquei no GitHub para referência futura.
Note que pequenas mudanças simplificaram bastante o código.
Sua lógica está bem complicada, você continuará tendo outros problemas montando código deste jeito. Eu acho que eu já havia falado isto para você em outra pergunta mas como a pergunta não está em sua conta você provavelmente criou outra conta.
Só uma coisa boba que ajuda entender o programa. Você está criando uma variável que vai guardar um cliente e chama ela de clientes. E cria uma variável que vai guardar vários clientes e chama ela de cliente. Vai funcionar mas esta inconsistência faz o pensamento correto mais difícil. Uma dessas variáveis provavelmente deveria ser local. A variável aux provavelmente não deveria existir. O nome desta classe Operacoes parece não se um nome apropriado. De outra forma talvez esta classe nem deveria existir. Me parece que está criando uma classe apenas por criar.
Comment: Por que a minha lógica está complicada? Seja mais especifico.
Comment: Teria muita coisa para dizer além do que eu já disse. Viraria um curso.
Comment: Na verdade a variável 'max' não existe acho que você se referiu a 'aux' mas ela tem que existe por que a cada cliente registrado soma mais 1 essa é minha intenção. Obrigado pela resposta.
Comment: Isto, eu digitei errado. Não existe razão para ela existir.

Problemas ao executar classe em Java


link não é chamado

Question: Tenho um codigo jQuery que gera uma div ele funciona tranquilamente, nele tenho o seguinte trecho
div += "
Coloque o seu veículo a disposição!
";

depois eu adiciono essa div e ela aparece na tela certinho, porem meu problema é que queria chamar o evento de outro botão ao clicar nesse link
$("#link_new_ad").click(function (){
    alert('teste');
    $("#bundle_ad_submit").trigger('click');
});

porem quando clico no link nada acontece, seu colocar o link no html em vez de colocar pelo append(div) ele chama o evento.
Alguem sabe o que ta acontecendo, e melhor como concertar?
Answer: Use $(seuelemento).on("click", function() {})
Isso ocorre porque o DOM já foi carregado, você precisa do evento ON para ficar ouvindo as mudanças da página.
Comment: @Rodrigo, você está aplicando o evento `on()` em um elemento que ainda não existe, isto não vai monitorar a inclusão do mesmo.
Comment: mano pode crer o que tu disse, mas por algum motivo não funcionou a respoda @pedro-camara-junior funcionou.
Comment: Rodrigo, fiz um teste com o `on`diretamente no console do navegador mas não consegui fazer funcionar, consegue postar um exemplo talvez?
Comment: Há outra sintaxe, tente $('body').on("click", "seuelemento", function() {})
Comment: http://api.jquery.com/on/
Comment: Usar seu JS antes ou depois do body também pode influenciar... É recomendado usar JS antes de fechar fechar o body.
Comment: @RodrigoMello, isto era uma recomendação dada pelo Yahoo nos primórdios da internet. hoje é interresante usar [](https://hacks.mozilla.org/2009/06/defer/)
Answer: Isso ocorre pois no você está atribuindo o evento click ao elemento antes de ele existir no HTML.
Como solução você deve criar o evento do click logo após adicionar a div ao HTML.

$(document).ready(function() {
  var html = "
Coloque o seu veículo a disposição!
";
  $('body').html(html);
  //Após adicionar no HTML atribua o evento ao link.
  $("#link_new_ad").click(function() {
    console.log('teste');
  });
});

Comment: Mas então adiciono a div em uma função apos uma chamada assincrona ajax. Você ta dizendo para adicionar o evento do click  dentro dessa função?
Comment: Pode crer deu certo, valeu cara vou por sua resposta como a certa.
Comment: Isso mesmo. Tentou utilizando o `on`citado pelo @RodrigoMello?
Comment: tentei mas não funcionou, mas ai quando coloquei a chamada dentro da função ai funcionou.
Comment: @MarciusLeandro No teu caso acho melhor utilizar o `on` da maneira citada pelo @TobyMosque
Answer: Amigão, vc pode chamar o metodo .click() direto, não precisa do trigger.
$("#link_new_ad").click(function(){
    alert('teste');
    $("#bundle_ad_submit").click();
});

Se nao funcionar, verifica se o $("#bundle_ad_submit") existe mesmo, se ele esta conseguindo achar esse objeto e se tem evento atachado nele.
Answer: Como o @PedroCamaraJunior apontou, você está tentando associar um evento antes que ele exista, neste caso o ideal é usar o metódo on() em algum parente mais próximo deste elemento e passar um seletor deste elemento como parâmetro.
Abaixo segue um pequeno exemplo de como adicionar conteúdo dinamicamente a pagina e não ter problemas com o bind dos eventos.

var tmplCarro = document.getElementById("tmplCarro").content;
var container = $("#container");
var addCarro = $("#addCarro");

addCarro.on("click", function () {
  var carro = $(document.importNode(tmplCarro, true));
  container.append(carro);
});

container.on("click", ".enviar", function (event) {
  var enviar = $(this);
  var linha = enviar.parent(".linha");
  var carro = $(".carro", linha);
  alert("Enviando Carro: " + carro.val());
});

<template id="tmplCarro">

     Carro:
      <input class="carro" type="text" />

    <input class="enviar" type="button" value="Enviar" />

</template>

<input id="addCarro" type="button" value="Adicionar Carro" />

Você até pode usar  $(document).on("click", #link_new_ad", function () { ... }) que irá funcionar, porém o recomendado é utilizar o parent mais próximo ao invés de document
Comment: Assim funcionou utlizando o `on`. +1
Answer: Eu utilizaria o seguinte trecho:
$("#link_new_ad").on('click', '#bundle_ad_submit', function()
{
     alert('teste');
})

Por que assim o evento on, "ouviria" o DOM e veria quando ele fosse carregado.

link não é chamado


Search ID list and match in excel

Question: I have a list of random emails and then a list of emails with IDs. I want to get the ID's from the list, to assign to my random list.
So
ID email                                ID  emails jumbled up
43 emailaddress1                         ?  emailaddress3
46 emailaddress2                         ?  emailaddress1
32 emailaddress3                         ?  emailaddress2

Thanks.
Answer: Index & Match will work for this:

D2 = INDEX(A:A,MATCH(E2,B:B,0),1)

Drag this equation down to your last Jumbled email to populate your IDs (in this example, down to D4). If your two tables are on separate sheets, you will need to adjust the equation accordingly.

Search ID list and match in excel


Initializing and Deleting a 2d Array

Question: I've looked at a few other threads, but can't seem to figure out how to delete a 2d array.
Here is how I'm initializing the array. num_items and capacity are predetermined variables:
int **P = new int *[num_items];
for (x = 0; x <= num_items; x++)
     P[x] = new int[capacity];

Here is how I thought I was suppose to delete it, however, it is crashing:
for(x = 0; x <= num_items; x++)
    delete [] P[x];
delete [] P;

To clarify, I want the array P to hold 1 extra of num_items. So if num_items = 7, than I want the array size to be 8 so that P[7] is valid.
Comment: Unless this is for educational purposes: Never call new/delete yourself, use smart pointers ([`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) and [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr)) instead.
Comment: @user2176127 *never* is a bit too much.  There are cases where you will need to manage memory yourself (which should be done in the context of a class), but they are rare.
Answer: Your comment "Don't need to add +1 to num_items" and your implementation of the for loop contradict each other.
Remember that arrays are 0-based, so P has valid indices 0 up to but not including num_items. However, in your for loop, x takes on the values 0 up to and including num_items.
Thus, the fix is likely
for (x = 0; x < num_items; x++)
    /* whatever */

All of this being said, can you use std::vector instances instead? Then, you don't have to worry about this sort of memory management.
Comment: I'd also suggest looking at http://www.boost.org/doc/libs/1_54_0/libs/multi_array/doc/user.html since using `vector` still means a potentially ragged matrix.
Comment: Sorry that comment was meant for something else and I meant to delete that before posting it
Answer: Your problem is your math:
int **P = new int *[num_items];
for (x = 0; x <= num_items; x++) // PROBLEM!
     P[x] = new int[capacity];

Arrays in C/C++ are 0-based, so when you declare it to have a size X, you can access all of the elements from 0 to X-1.  Your less-than-or-equal-to comparison will attempt to access element X, which is memory outside the bounds of what you have declared, so you get undefined behavior.  What you want is:
int **P = new int *[num_items];
for (x = 0; x < num_items; x++)
     P[x] = new int[capacity];

And then
for(x = 0; x < num_items; x++)
    delete [] P[x];
delete [] P;

That said, using std::vector would be the better solution.

Initializing and Deleting a 2d Array


jQuery bind input

Question: Before HTML5, we had to use the onkeypress event (or similar) to detect when a user adjusts the text in an input field. This often created synchronization problems and didn't work at all with on-screen keyboards, thus requiring us to bind multiple events. HTML5 solves this problem by defining the oninput event. Since HTML5 is not yet universally supported, however, it is often safer to use the oninput event along with the onkeypress event for backwards compatibility.
While writing a validation script, I recently discovered that the following works in jQuery:
$('input').bind('input', function() {...});

However, there seems to be very little documentation (if any) on this. My question is this: since this is implemented in jQuery (which should already be backwards compatible), is it necessary to include 'backup' events such as onkeypress?
I suppose there's nothing wrong with throwing a few extra bindings in:
$('input').bind('input keydown mousedown', function() {...});

but it would be nice to know whether or not the extra bindings are necessary.
Answer: I think you should think about backward compatibility because it's not supported in all browsers and for more information you can see here.
Comment: Right. I guess my question is actually about jQuery though. When I use the `input` binding through jQuery, does it take care of backwards compatibility?
Comment: Here is an answer on [SO](http://stackoverflow.com/questions/6669091/bindinput-function-not-working-in-ie8).
Comment: So it looks like even the jQuery version is not backwards-compatible. This surprises me, because several jQuery bindings are 'normalized' so that they work the same in all browsers. Oh well, I guess I'll be using multiple bindings...
Comment: I think multiple binding will be better. :-)

jQuery bind input


Question about unique pointer of classes (initialisation of variables in .h VS in constructor)

Question: i'm a begginer starting with unique pointer unique_ptr and I have a question about them :
If I've got a class A and inside it's .h I have an other class B like this :
class A{

   B b;

public:

   A();
}

(consider the includes)
If I want to create an unique_ptr of A what is the difference for B in those cases :
(unique_ptr a = make_unique())
Case 1 :
class A{

   B b = b(1);

public:

   A();
}

and Case 2 :
class A{

   B b;

public:

   A();
}

inside the constructor of A() :
A::A() {
   b = b(1);
}

It seem to be different for the use of B inside A for each of them, but I can't see why.
Comment: The implementation of `A` won't change just because someone else creates a `unique_ptr`.  I'm not sure what you're getting at here.
Comment: @TimRoberts It's more about B , what could be the difference with it If I try to use it with A (like A->getB().doStuff() or anything with the use of B from A)
Comment: Read my answer.  The implementation of A does not change.  A does not know.  `b` is private, so no one outside of the class an use it anyway.
Comment: Should the instances of `b(1)` actually be `B(1)`?
Answer: In case 1, when A is constructed, it directly initializes A::b with 1.
In case 2, when A is constructed, it first default-initializes A::b, and then assigns it another B object that is initialized with 1.
This is no effect whatsoever on how unique_ptr or make_unique() operate.
Answer: The constructor of c++ is different than constructor in other OOP language.
It's separate in 2 part.

member initialization .
function body.

#include <iostream>
struct BB{
    int num;
    BB(int in):num{in}
    {
        std::cout << "ctor BB value=" << num <<"\n";
    }
};
struct AA{
    BB b{1};
    AA()
    {
        b = BB{2};
    }

};
struct AB{
    BB b{1};//default initialization
    AB():b{2}//member initialization
    {
      //function body
    }

};

int main() {
   std::cout << "-- create AA \n";
   AA a{};
   std::cout << "value AA.b.num=" << a.b.num << "\n";
   std::cout << "-- create AB \n";
   AB b{};
   std::cout << "value AB.b.num=" << b.b.num << "\n";
}

result is
-- create AA
ctor BB value=1
ctor BB value=2
value AA.b.num=2
-- create AB
ctor BB value=2
value AB.b.num=2


Windows Servers with Citrix + Credential Guard > CPU use from average 30% to 90-100%. Ideas?

Question: It has been observed that Windows Servers with Citrix and "Credential Guard" feature turned on; have jumped in CPU use from average 30% to 90-100%. This is a work in progress and Microsoft has acknowledged it but has there been anyone experiencing the same issue?
Answer: Posting here for everyone else experiencing the same problem, after long troubleshooting series of events with Microsoft engineers;
This is caused by AppSense querying LSAISO.exe.
So to find out if it is impacting you, there are two qualifiers:
1- looking at process CPU time, LSAISO stays above 25%.
2- AppSense is installed
If you don't have both conditions above, your problem most likely has a different root cause.
Troubleshooting:

We have tried to disable the credential guard on the test machine, to see, if we disable the credential guard does the CPU usage comes to normal on the Citrix machine or not, found that once its disabled, the CPU usage was normal.

Find the commands which we ran to disable the credential guard.

We have logged into the server on console that has high CPU.
Open an elevated command prompt and run these commands:
cd %systemroot%\System32
mountvol X: /s
copy .\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y
bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"
bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
manage-bde -protectors -disable %systemdrive%
REG DELETE HKLM\Software\Policies\Microsoft\Windows\DeviceGuard /v EnableVirtualizationBasedSecurity /f
REG DELETE HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard /v EnableVirtualizationBasedSecurity /f
REG DELETE HKLM\Software\Policies\Microsoft\Windows\DeviceGuard /v LsaCfgFlags /f
REG DELETE HKLM\SYSTEM\CurrentControlSet\Control\Lsa /V LsaCfgFlags /F
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO,DISABLE-VBS
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:
mountvol X: /d
shutdown -r -t 0
When prompted we must hit F3 to disable LSAISO and then hit any key to confirm the change
When prompted we must hit F3 to disable VBS and then hit any key to confirm the change

After disabling, we have followed the below steps to make the LSAISO.exe process to run in debug mode to see, if in debug mode we see the same issue or not, however we have found that, we didn't notice the issue.

Run these commands from an elevated command prompt and reboot:
REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Lsa /V LsaCfgFlagsTest /t REG_DWORD /d 1 /f
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" /v DisablePagingExecutive /t REG_DWORD /d 1 /f
Reboot the computer verify lsaiso.exe is running.
Right-click the process in taskmgr and verify Create Dump generates a dump greater than 0K in size. If it does, then lsaiso.exe is running in normal memory and can be debugged.

Resolution :
Before collecting the required logs, I have tried to cross check and found that, on the Citrix machine where we have appsense installed, this has a known issue with that, hence, to apply the fix we have followed the below process, and we have found that, CPU usage came to normal state now.
Open Regedit and navigate to:
HKLM\Software\AppSense\Environment Manager\ASModLdr
Edit the "Exceptions" value.
Add a new line at the bottom containing LsaIso.exe (the fourth letter is a capital I for India, not lower-case L for Lima)
Save the value.
Reboot the machine.
We have monitored the CPU and found that it came to normal state now. (LsaIso shows 0% CPU and overall CPU dropped by 60%)


JQuery .attr() not working with specified IDs

Question: I'm pretty new to JQuery(and JS). I am trying to make a very simple thing that will change my image attribute and for some reason it's not working. I've been breaking my head over this for the past hour and I can't seem to find a logical reason for why it's not working. I've tried $("#thumbnail-"+id).attr(...) as well and it doesn't work. I couldn't figure out why. So I broke things down to the code below, still doesn't work. For some reason the attribute doesn't change.
Here's my code( I commented it to make things easier):
$(".innerImage").click(function (e) {
    var imageName = ($(this).find('img').attr('src').split('/'))[2]; //returns something like 4.jpg
    var id = (imageName.split('.'))[0]; //returns just 4 (from 4.jpg)
    var thumb = "#thumbnail-"+id; //returns #thumbnail-4
    var thumbnail = 'product/thumb/'+id+'.jpg'; //returns product/thumb/4.jpg
    var full = 'product/full_size/'+id+'.jpg'; //returns product/full_size/4.jpg
    $(thumb).attr('src', thumbnail); //This is the crazy part that doesn't work
    alert(1); //Did a trace and it reached here.

});

Stuff that worked but I cannot use them:
So the weird part here is that the following worked:
$('img').attr('src', 'product/thumb/test.jpg');
$('#thumbnail-4').attr('src', 'product/thumb/test.jpg'); //this worked perfect. Notice how it's just that specific id, where I didn't concatenate the 4 using the method in my code. The latter is more general

However the above(latter) one messes up all my images and not the specific one I want which is #thumbnail-id(where id = 1,...). Could anyoune point out what I'm doing wrong. The only thing I can see is that it's not allowing me to concatenate my strings and use them.
Edit: HTML

            "

            <button class='zoomImg intense' data-image='product/full_size/4.jpg' id='zoomImg-4'></button>

Comment: `'product/full_size/'+id+'jpg'` should give you `product/full_size/4jpg`, without the dot. Use the developer tools to inspect the element. And please be specific, what does "`attr()` not working" mean?  You don't see a new image? The `src` value on the element is not changed at all? Hell kittens appear and mewl you to death?
Comment: There is zero chance that `$('#thumbnail-4').attr(...)` and `id='4'; $('#thumbnail-' + id).attr(...)` will do something different in the same context. Re-check your `id` with `console.log("[" + id + "]")` (make sure you don't have any rogue space issues).
Comment: Can you post your HTML? I'd like to toss this into a fiddle to work out for you.
Comment: You may also have duplicate elements with `id="thumbnail-1"` (or whatever those specific, not working IDs are)
Comment: Well, you need to post some HTML, preferably in a JSFiddle example that replicates the problem
Comment: I made a fiddle for you here but of course it works as expected ~ http://jsfiddle.net/ubdkaeur/
Comment: Well, clicking the first `.innerImage` won't do anything (other than set the `#thumbnail-4` image to be the same) and clicking the second one won't do anything as there is no `id="thumbnail-4-002"` element
Comment: We assume you have 2 divs rightSide one "" and another one "", right?
Comment: Yeah. Both are there @Giuseppe
Comment: Add console.log("value is: "+$(thumb).attr('src')); and you'll see if it gets what you expect.
Comment: @Giuseppe Thanks. value is: undefined showed me where I went wrong. It's like Phil said.
Comment: *"It's like Phil said"* - Wait, what did I say?
Comment: @Amadan `For some reason the attribute doesn't change.`So yeah, the src atrribute is not changed at all.  And thanks for pointing out the 4.jpg edited it.
Comment: What do you mean by *"messes up all my images and not the specific one I want"*? Messes them up how?
Comment: @Phil Here it's just to show that I don't want to have all my `` attributes changed. Just the ones with `thumbnail-id`. When I tried to replace `thumbnail-id` with just `img` all the attributes were changed, thus a big mess up
Comment: @Amadan that's why I've spent one hour on it and can't find a solution. I use `$('stuffHere'+id)` all the time and they work.
Comment: Oh, by *"above one"* you meant the *latter* code snippet. Only thing I can think of is that `id` does not get assigned what you think it does. You should set a breakpoint in the code and step through, checking each value.
Comment: @Amadan console.log shows no spaces.
Comment: @Phil If there were repeating thumbnail, a direct use of `('#thumbnail-4')` for example, would not have worked as well. However a direct use works.
Comment: Ah, I thought you meant only specific IDs weren't working
Comment: It's quite specific, since all that needs to work is "#thumnail-id" and not "img" (which is the general img tag for all images).
Comment: I noticed in your code comment you have `var thumb = "#thumbnail-"+id; //returns thumbnail-4`. Shouldn't that be *" returns #thumbnail-4"*? Just a typo?
Comment: You're right, @Phil now it works. Looks like I had a logical error and I didn't properly trace it. It's all working now. Thanks
Comment: Please provide a FIDDLE
Comment: There is no id="thumbnail-4-002".
Answer: What looks to be happening is the following:
When you select the first image, 4.jpg, the id gets set to 4. In which case you're able to target '#thumbnail-4' correctly. However, when you click on the second image, 4-002.jpg, the id gets set to 4-002. So the script is looking to update the source of #thumbnail-4-002 which does not exist.
I put together this fiddle to show the disconnect.
http://jsfiddle.net/fd2cwm8y/
My suggestion for this would be to give the thumbnail a unique ID so it does not depend on the id value you're retrieving from the clicked image like I have thrown together here:
http://jsfiddle.net/7qt8wzot/
I hope this helps!
Comment: I fixed it already but this is the correct answer. Thanks :)


ObjectiveC/iphone: convert an array of dicts to an array composed of a certain attribute of each dict

Question: Looking for the most succinct way to convert an array of dicts to an array composed of a certain attribute of each dict. eg.
<code>[ { name => 'Visa', value => 'VI' }, { name => 'Mastercard', value => 'MC' }]
=>
 ['Visa', 'Mastercard']
</code>
Answer: This should do the trick:
<code>NSArray *nameArray = [yourArray valueForKey:@"name"];
</code>

valueForKey: Returns an array containing the results of invoking
  valueForKey: using key on each of the
  receiver's objects.
Comment: awesome. I was looking at NSArray docs but missed that one. thank you!


Composer hangs on "Resolving dependencies through SAT" on 4.2

Question: Things I've tried:

Removing everything except for Laravel (version 4.2.*) - This completes but still hangs for around 5 minutes
Updating composer
Removing /vendor
Doing clean Laravel 4.2 install (hangs around 3 minutes)
Doing clean Laravel 5 install (doesn't hang at all)
Turning off xdebug completely (doesn't seem to make a difference)

With all my packages, I've seen composer complete but only when I left it running overnight. I can't deploy to forge at all because it times out! This only started happening two or so weeks ago.
Comment: `Turning off xdebug completely (doesn't seem to make a difference)` - This should make a **huge** difference, especially on machines without an SSD, or without a high-end Intel chip, or both. Are you *sure* it was turned off? I've seen this issue before on another one of my colleagues development machine, where composer would take hours to do a simple update. The issue ended up being a corrupted composer installation. Wiping the system of the composer artifacts and re-installing worked great.
Comment: OK, yes, it did make a big difference (had turned it off in wrong php.ini), but it's still slow enough to time out my forge server. The bottom line is when something goes from taking 10 minutes to 10 hours (even with xdebug enabled), there's something bigger going on.
Comment: I don't disagree with you whatsoever. I think there's other things going on here, maybe there's an issue with DNS resolution, or a Firewall issue. Can you `strace /usr/bin/composer` and see what's happening while performing `composer update`? *sidenote* strace will dump ALOT of stuff out, so it's kind of a needle in the haystack, but it's definitely useful. There might be something better to debug this, however. I did also find a tip to `composer config --global repo.packagist composer https://packagist.org` which requires the setup to use HTTPS and seemed to fix the issue for others.
Comment: It happens on all of our dev environments, even with a completely new 4.2 install. I'm almost sure it's due to Laravel 4.2 dependencies because 5.2 doesn't hang at all at this point. And I switch to https earlier while trying to debug, might have helped but benchmarks are with that already done.
Comment: Can I see your `composer.json` so I can try to install it locally? We maintain 4.2 LTS stacks and don't have this problem.
Comment: https://jsfiddle.net/n10tvgcw/
Comment: Same thing happens with 4.2.* and 4.2. And, they complete. I can just tell that they hang for a minute or two on "Resolving Dependencies Through SAT" where 5 doesn't at all. And, nothing we did triggered this to happen, so I just have to think it's something was updated with a dependency that doesn't place nice with the other packages...
Comment: @SabrinaGelbart did you found a solution to this? i am also going nuts with the slowness of composer.
Comment: Yes, kinda - 1) if you're not already you can run 'composer update' on one machine and then commit your lock file then run 'composer install' on each other machine 2) declare versions as explicitly as possible.
Answer: For all looking for an answer...here's what helped increase performance:

Commit composer.lock: if you're not doing this already you can run 'composer
update' on one machine and then commit your lock file then run
'composer install' on each other machine. This saved our deployment process!
Generally declare versions as
explicitly as possible.

and/or

update your Laravel version!
Comment: Didn't actually solved the issue, but made me remember about the composer.lock file, which I only deleted and the problem was solved.


Select column_name from cols return nothing although column exists

Question: i am trying to execute this statement in Oracle 9i.  However it seems that the result set is empty although J am very sure that there are many columns with the name ID.
select * from cols where column_name like '%ID%';

Also, the following statement returns an empty result set.
select * from cols;

May I ask if this could be due to user privilege?
Thanks!
Answer: The Oracle Reference says of COLS:

"COLS is a synonym for USER_TAB_COLUMNS."

This suggests a simple answer to your conundrum: you are connected to the database through a user which owns no tables (or views).  Either change your user or try selecting from ALL_TAB_COLUMNS (which shows results from all the tables/views you have privileges on).
Comment: I think somewhere along the line before your post a member mentioned that this could also be affected by a feature called the Virtual Private Database that is since version Oracle 8i, however i think the post has been removed, APC would you have any comments on this? Kindly. :)
Comment: @ChinBoon - Virtual Private Database (AKA Fine-Grained Access Control) is a mechanism for invisibly restricting access to rows of data - and columns after 10gR2 - by defining additional filters which are applied to all DML statements.  Check out DBMS_RLS to find out more.  I don't think it is relevant to your situation, because VPD would not be applied to the data dictionary.