How to display my data in a visually pleasing way?

Question: I have some funky data that I'd like to put into a final presentation form and I was hoping to get some creative ideas on how to do it. My data compares measurements of different lengths, so for example I have 52 week long samples of 6 different chemicals (times several duplicates), 26 2 week long samples, 12 month long samples, 4 quarterly samples, 2 semiannuals and an annual sample. I have compared the accuracy of each duration with one another for a total of 15 comparisons (week vs 2 week, week vs month, etc) to find how much one deviates from another on average by computing the % bias, where negative bias indicates that the longer of the 2 samples under-reports and positive bias indicates that the shorter of the 2 samples under-reported. So I have an average % bias and a 95% confidence interval for each of 6 chemicals for each duration comparison. My confidence intervals are of varying widths because I obviously have many fewer data points for comparisons involving annual samples. An example is given below:
Chem1
     week v biweek    week v month    week v quarter    week v semiannual    ....
low95    -10               -12              -15               -17
mean      0                  2                2                -1
high95    10                14               17                15

How might I pack this into one nice looking graphic (or color coded table, or something) that can convey the average bias for each chem and the accompanying confidence interval (maybe highlighting those with greater power?) and also for each duration comparison (ideally maintaining some visual representation of relative time lengths). I would be content having 6 graphics (one for each chemical), but I don't think I want 15 (one for each comparison). I was thinking that a color ramp would help ad an extra dimension to it, but I don't really know how to implement that in R. Any creative solutions? Help on the color-ramping? Please keep in mind that I'm working in R and I'd say my R skills are about intermediate. Thanks a ton!
Answer: Here are some ideas
dataset <- expand.grid(Chemical = factor(1:6), Comparison = c("week vs biweek", "week vs month", "biweek vs month"))
dataset$Bias <- runif(nrow(dataset))
    dataset$Width <- rnorm(nrow(dataset), mean = 3)
dataset$LCL <- dataset$Bias - dataset$Width
    dataset$UCL <- dataset$Bias + dataset$Width
dataset$Class <- cut(dataset$Width, c(0, 4, 8))
library(ggplot2)
ggplot(dataset, aes(x = Comparison, y = Bias, ymin = LCL, ymax = UCL, colour = Chemical, size = Class)) + geom_hline(yintercept = 0, linetype = 3) + geom_errorbar(position = position_dodge(0.5)) + geom_point(position = position_dodge(0.5))
ggplot(dataset, aes(x = Comparison, y = Bias, ymin = LCL, ymax = UCL, colour = Class)) + geom_hline(yintercept = 0, linetype = 3) + geom_errorbar(position = position_dodge(0.5)) + geom_point(position = position_dodge(0.5)) + facet_wrap(~ Chemical)

Comment: I really like that 1st one. I've only recently been exposed to the glorious world of ggplot2. You've not only given me a place to take off from, but you've got me pumped on graphs! Thanks! PS I'll vote it up as soon as I have the rep to do so.


Date format on user profile form shown incorrectly - how to change

Question: I added a date to the user profile form under admin/config/people/accounts/fields. The field is of type 'date', the widget of type 'select list' and I only collect year, month and day.
Without altering anything the date entry widget is shown on the form in the order year-month-day.
Since the order in the Netherlands should be day-month-year, I set out to change the date format by:

Adding a new custom format d/m/Y under admin/config/regional/date-time/formats
Create a new date type called 'test' and referencing the custom format from the previous step under admin/config/regional/date-time
Changed the date display format to the 'test' type, under admin/config/people/accounts/display - press update and save the settings

In the date preview of admin/config/people/accounts/display, the date is shown as DD-MM-YYYY which is the format I want.
Now, going to the user profile page under user//edit, the date order shown as month-day-year.
I have tested this on a clean installation of Drupal 7.33 and the only module added is the date module 7.x-2.8.
How can I change the display order for this specific field?
Kind regards,
Eric van der Staaij
Answer: Date entry format is configurable, what you did was changing the way the date will display on content but not on create content form. To change it go to your field configuration page on content type then find more settings and values collapsed fieldset and inside it look for date entry options and change to whatever.
https://docs.google.com/a/srijan.in/file/d/0B9FG53CLjf-YdEFfdzVEV1hmcWc/edit?usp=drivesdk
Comment: Ah. Thanks. I now found it. It was a collapsed fieldset indeed and I totally looked over it. Thanks!
Answer: Please refer the Community Documentation of Usage example of date elements within forms in the Date API form elements for the solution.
Thank you.
Comment: That is for programmatticaly adding or modifying forms. Not when using Drupal's user interface to manage and display fields.


Como escrever e aparecer em algum lugar o que eu escrevi

Question: Bom, nos sites hoje em dia são encontrados algumas coisas que eu não sei explicar, por exemplo, pense em um formulário pedindo seu nome, você preenche, e na mesma hora aparece encima o seu nome, como se você estivesse digitando e aparecendo no formulário e encima. Como posso fazer isso?
Comment: Por favor, selecione a resposta que resolveu ou te ajudou a resolver o problema, escolher a melhor resposta ajuda as próximas pessoas que tenham a mesma dúvida.
Answer: Isso pode ser feito com javascript, manipulando o DOM a partir de eventos.
Neste exemplo, cada vez que o valor do input for alterado, o valor da div também será.

 var alteraValor = function () {
    document.getElementById('a').innerText = document.getElementById('b').value;
}
<input id="b" oninput="alteraValor()"/>

Comment: Bom, eu queria que quando escrevesse aparecesse como div, tem como?
Comment: Sim, @Fkda só mudar o elemento a seu alterado e sua propriedade.
Answer: Usando jQuery pode ser algo assim:

<form>
    <input id="nome" value="" />
</form>

$("#nome").keyup(function() {
    $("#div_nome").text($(this).val());
});

Comment: Você incluiu o código `jquery`?
Comment: Não apareceu nada. Poderia me ajudar?
Answer: Uma outra forma de se obter o resultado desejado:

window.mostrarTexto= function(valor){
  var campo = document.getElementById("campo").value;
  div.innerHTML = campo;
}
<input id="campo" type="text" onkeyup="mostrarTexto(this.value)"/>

A diferença dessa forma com a apresentada pelo @AlexSander e basicamente o evento que chama a função

onkeyup -> função é acionada quando o usuário solta uma tecla
oninput -> função é acionada quando o elemento recebe uma entrada do usuário

Vale lembrar que oninput e um atributo adicionado no HTML5 o que pode dificultar o seu uso em navegadores mais antigos...


Calculate the side of rectangle using only length, no area or perimeter

Question: My geometry is a little rusty due to not doing it for so long. I  am trying to find the side of a rectangle by only knowing one sides length. Is this possible?
Length of one side is $0.21875$. I have gone about this using trig by dividing the rectangle into half creating two right angle triangles with theta thus equaling 45 degrees.
Is this the correct way of going about this?
Answers I get are:
$0.1350496052$ (Taking $0.21875$ as Opposite angle)
and
$0.354332582$ (Taking $0.21875$ as Adjacent angle)
Calculations:
$\tan(45) = \frac OA$
Thanks
Comment: If it is a rectangle divided into two equal halfs through a long diagonal, the angles would not be 45 degrees.
Comment: @Gordon why would they not be? To clarify I mean two equal triangle halves if that was not clear. All interior angles should add up to 360. Remainder after dividing into half would be 180 - right angle. Leaving 45 for the two remaining angles
Comment: Suppose a diagonal was drawn from the bottom left to the top right of the rectangle. Depending on how long the rectangle is, the angles may not be 45 degrees; they could be 50 and 40, 81 and 9, etc.
Comment: A consequence of @Gordon's comment is that it is impossible to compute the length of the other side without more information
Comment: @Patricio Thank you very much
Answer: As pointed out by Gordon, when a rectangle is divided into two parts of equal area through a long diagonal, the angles would not be $45^{\circ}$
Construct a rectangle $ABCD$ and draw $BD.$ Now $\angle ABD=\angle BDC$ as they are alternate angles. If we assume (as you said) that $\angle ABD=\angle DBC=45^{\circ}$ then $\angle BDC$ must also be $45^{\circ}$ but then $\triangle BCD$ will become isosceles meaning $BC=DC$ but it cannot be true as in a rectangle length$\ne$breadth. So we proved that $\angle DBC$ is not $45^{\circ}$ hence we proved that diagonal does not divide $\angle B$ equally.
For your main question, we can't determine the breadth of a rectangle if we just know it's length. The information is insufficient.
Comment: @NotReallyOliverTwist you're struggling... that's a good thing..this means that you're actually trying to learn things...this happened with me also when I first learnt geometry.. it's undoubtedly tough (at least for me)....now if you want to generate some examples....draw two parallel lines at a distance of $3$cm and again draw two different parallel lines at a distance of $2$cm...but the lengths of all $4$ lines should be same ...say $5$cm...then join both lines by their end points one by one to get two quadrilaterals...both are rectangle of same length but of different breadth
Comment: It's been so long since I have had to do any of this I completely forgot about alternate angles and so forth. Makes sense.

How would I go about calculating the length then knowing only it has a right angle and one sides length? Alternatively I would be happy to figure this out on my own with just a nudge in the right direction where to learn to do this again. Thanks
Comment: @NotReallyOliverTwist you cannot evaluate the breadth of the rectangle if you just know the length...the information is insufficient..and welcome :)
Comment: Thank you very much for your time. Would explain why I was struggling to find examples online.


Console.time always returns 0.000ms

Question: I'm using node-webkit to create a album manager and I'm setting up a recursive scan to find all my photos. I'm scanning some 10k files, but console.time just keeps returning 0.000ms. I know the scan is happening pretty quick, but it's not that quick. Am I doing something wrong?
var fs = require('fs');
var path = 'I:/pictures/';

console.time('read-directory');

var scanDirectory = function(path) {
    fs.readdir(path,function(err,files) {
        if(err) {
            console.log(err);
        } else {
            files.forEach(function(file) {
                fs.stat(path + file, function(err,stats) {
                    if(err) {
                        console.log(err);
                    } else {
                        if(stats.isDirectory()) {
                            scanDirectory(path + file + '/');
                        } else {
                            console.log(path + file);
                        }
                    }
                });
            });
        }
    });
}

scanDirectory(path);

console.timeEnd('read-directory');

Comment: fs.readdir is asynchronous. console.timeEnd is being called before it ever reads anything.
Answer: You are using fs.readdir which is asynchronous. So your timer is not depending of your scanDirectory execution.
In fact, it's just launching your function when you call scanDirectory(path) then directly after stop the timer.
If you want you can use fs.readdirSync which will prevent to jump to the timer end as it's a synchronise function. The problems, is that will freeze your application (if your use it's directly like that) during this time and problably slow your execution.
In order to get the time of execution of your asynchrone function you can use the profiler tool of Node-webkit. But you will need to filter and sum them manually...
The other solution is to use timely (it's an npm package ) that can time synchronous or asynchronous functions.

Console.time always returns 0.000ms


How do I tell git-svn about a remote branch created after I fetched the repo?

Question: I'm using git-svn to work against my company's central Subversion repository. We've recently created a new feature branch in the central repo.
How do I tell Git about it? When I run git branch -r I can only see the branches that existed when I ran fetch against the Subversion repo to initialize my Git repo?
Comment: Answers from here: http://stackoverflow.com/questions/13376917/add-git-branch-after-initial-fetch-in-the-same-svn-remote might also be useful.
Answer: You can manually add the remote branch,
git config --add svn-remote.newbranch.url https://svn/path_to_newbranch/
git config --add svn-remote.newbranch.fetch :refs/remotes/newbranch
git svn fetch newbranch [-r<rev>]
git checkout -b local-newbranch -t newbranch
git svn rebase newbranch

Comment: @phpguru Try removing the -t option flag so it becomes 'git checkout -b local-newbranch newbranch' don't forget to include the remote's prefix to newbranch (ex. origin/newbranch).
Comment: I get `fatal: Cannot setup tracking information; starting point 'newbranch' is not a branch.` at the git checkout step.
Comment: If I could upvote this like eight times, I would. Finally, a way to add an svn branch that's added in a nonstandard location!
Comment: just adding this link to the docs as a reference http://www.kernel.org/pub/software/scm/git/docs/git-svn.html
Comment: From .git/config it is quite easy to understand how remote branches can be configured from single / multiple repositories.
Comment: The branch doesn't seem to be based on trunk/master, the first commit is the copy. Can you rebase the newbranch on the commit in trunk where it is copied from?
Comment: Unfortunately, this looses svn branch history. E.g. your `git blame` will render useless, amongst other stuff. See [MatrixFrog's answer](http://stackoverflow.com/a/4416172/531179) for a better solution.
Comment: minor point, but when this answer mentions [-r], I had to do `-r21000:HEAD`
Comment: The 4th command no longer works on current versions of Git. Omit "-t" and you should be OK. See here for details: http://stackoverflow.com/q/19712735/745575
Comment: That link to the docs is down. I looked all over for a new link, but I can't find any "official" git-svn docs. Does anyone have a good link to replace this with?
Comment: isn't the whole point of --stdlayout so that git svn can know some of these things. IMO There should be a git svn command which does the first 3 all in one shot based off --stdlayout
Comment: This approach may be required if the branch location is in a non-standard location, but if you use standard locations and pulled in the branches that already existed with the initial clone, then git svn fetch is all you need (as suggested in the other answer below). Note you need 'git svn fetch' explicitly not just 'git svn rebase'.
Answer: If you want to track ALL the remote svn branches, then the solution is as simple as:
git svn fetch

This will fetch ALL the remote branches that have not been fetched yet.
Extra tip: if you checked out only the trunk at first, and later you want to track ALL branches, then edit .git/config to look like this and re-run git svn fetch:
[svn-remote "svn"]
        url = https://svn/path_to_repo_root/
        fetch = path_to_trunk:refs/remotes/git-svn
        branches = path_to_branches/*:refs/remotes/*

The key points are url should point to the repository root, and the paths defined in fetch and branches should be relative to url.
If you want to fetch only specific branches instead of ALL, there is a nice example in git svn --help:
[svn-remote "huge-project"]
        url = http://server.org/svn
        fetch = trunk/src:refs/remotes/trunk
        branches = branches/{red,green}/src:refs/remotes/branches/*
        tags = tags/{1.0,2.0}/src:refs/remotes/tags/*

With older versions of git-svn, once you specified branches like this, you might not be able to get new branches with git svn fetch. One workaround is adding more fetch lines, like this:
[svn-remote "huge-project"]
        url = http://server.org/svn
        fetch = trunk/src:refs/remotes/trunk
        fetch = branches/blue:refs/remotes/branches/blue
        fetch = branches/yellow:refs/remotes/branches/yellow
        branches = branches/{red,green}/src:refs/remotes/branches/*

Another workaround by @AndyEstes: edit .git/svn/.metadata and change the value of branches-maxRev or tags-maxRev to a revision before any newly-specified branches or tags were created. Once you've done this, run git svn fetch to track the new svn remote branch.
Comment: THIS SHOULD BE THE ACCEPTED ANSWER! @janos, you just saved me hours of headache! If you ever come to India, I'll take you out for a beer!
Comment: Editing ```.git/svn/.metadata``` was very helpful! I was adding extra branches in my ```.git/config```, which ```git svn fetch``` didn't pick up on -- because the metadata revision number was "too far ahead".  In one case, only the last commit from a branch was fetched.  I manually got rid of the faulty branch (renamed ```.git/svn/refs/remotes/svn/qa/XYZ``` to ```.git/svn/refs/remotes/svn/qa/XYZ~```, dropped its existence in ```.git/packed-refs```, etc)... picked an "earlier" revision number for the metadata... ran ```git svn fetch``` to finally get a full history w/ correct, connected graph.
Comment: If you have already fetched the revision to which performed svn branching before you set those settings, you might want to do git svn reset.
Comment: Or: `git svn fetch --all`.
Comment: I am also unable to change the branches line and need to use additional fetch lines.
Comment: I like this solution better because, this one was able to show me nice graph in git also was able to see the history in files. With the accepted solution, it treated each branch with its own history and only showed the last commit (one that created the branch) and I was not able to see file change history.  Only problem I have is not being able to add the branches later as you indicated.. I hope this get resolved soon.
Comment: Thanks, @AndyEstes. I needed to do this to get git-svn to find a branch I wanted to add (when my git-svn repo was already fully up to date with SVN, but did not yet include the branch).
Comment: Does anyone know if you can have whitespace or subfolders in the branches like this?
branches = branches/{58/red,green 3}/src:refs/remotes/branches/*
I'm getting a 'invalid pattern in' error when I try to fetch.
Comment: This was exactly what I needed for dealing with an SVN repository where the "trunk" is also in the branches folder.  Looks like setting up the trunk to point to the exact path and then doing the {} for limiting the branches that are pulled should work.
Comment: Changing tags-maxrev is what worked for me to pick up new branches.  Thanks!
Answer: It appears I just needed to git svn fetch; somehow I had convinced myself that would fetch the entire repo instead of just the changes.
Comment: @mitjak Why is it not the correct answer, if it's the solution?  I don't understand the subtlety of the response.
Comment: It works fine when the branch was created after the clone, I do it all the time.
Comment: 'a solution' maybe not 'the solution'
Comment: @rholmes: I'm pretty sure mitjak means that that's the solution to your problem but not the answer to the question you asked. (Because you asked the wrong question; as you misinterpreted the issue at the time.)
Comment: This works when branch existed at the moment you cloned svn repository into git. It will not work if branch in svn repository was created afterwards.
Comment: This is what helped me, but neither this nor the accepted answer is complete. This answer assumes the setup is already correct, while the accepted answer assumes that it isn't. A complete answer wouldn't assume either.
Answer: Maybe I messed it up somehow but I followed the instructions in vjangus' answer and it almost worked. The only problem was that newbranch didn't appear to be branched from the trunk. In gitk, it was kind of "floating" all on its own; it had no common ancestor with the trunk.
The solution to this was:

Find the SHA1 of the last commit that happened on trunk before the branch was created.
Find the SHA1 of the first commit on the new branch (message is probably "Created new branch, copied from trunk@12345" or something)
git diff-tree <sha1 from step 1> <sha1 from step 2> -- there should be no output. If there is output, you may have selected the wrong commits.
git checkout local-newbranch then git rebase <sha1 from step 1>. This will rebase local-newbranch onto the new tree but remotes/newbranch will still be disconnected.
Go to the file .git/refs/remotes/newbranch and edit it to contain the full SHA1 of the new commit (on the rebased newbranch) that corresponds to the old commit it's currently pointing at. (Or maybe use git-update-ref refs/remotes/newbranch <new-SHA>. Thank you inger.)
The next time you git svn dcommit to newbranch, you'll get a bunch of messages about it updating some log. This is normal I think.

I recommend keeping gitk --all open the whole time and refreshing it often to keep track of what you're doing. I'm still sort of new to git and git svn so please suggest improvements to this method.
Comment: Thanks, this sounds useful. About 5. probably 'git-update-ref refs/remotes/newbranch '  is the safer option.
Comment: vjangus solution always creates the new branch disconnected from the trunk. I assume this is because of the way SVN itself has no clue on how the actual content is copied around.
Comment: Just tried vjangus' way again and it worked perfectly. I'll leave this here anyway since it might be valuable to someone...
Comment: My experience with a large git-svn repo is that svn branches are always created in git detached from the trunk. There ought to be some way to connect them, but I haven't taken the time to figure it out. AFAIK, you can't rebase the git branch that is connected to the svn branch, because that will mess up the dcommit logic. We've just learned to live with it.
Answer: A simplification of vjangus' answer:
If you're using the standard layout in SVN and have done the usual svn init, git-svn will do the config stuff for you. Just:

Find branch-copy revision in SVN
Fetch that revision with git-svn
Create new local branch tracking remote

An example. SVN url is svn+ssh://email@example.com/repo. SVN branch I'm looking for is newbranch. Local git branch (tracking remote newbranch) will be git-newbranch.
Step 1: find the branch-copy revision

    # svn log --stop-on-copy svn+ssh://firstname.lastname@example.com/repo/branches/newbranch | tail -4
    r7802 | someone | 2014-03-21 18:54:58 +0000 (Fri, 21 Mar 2014) | 1 line

    branching HEAD to newbranch
    ------------------------------------------------------------------------

So the branch point in SVN is revision 7802.
Step 2: Fetch the revision

    # git svn fetch -r 7802
    Found possible branch point: svn+ssh://firstname.lastname@example.com/repo/trunk => svn+ssh://firstname.lastname@example.com/repo/branches/newbranch, 7801
    Found branch parent: (refs/remotes/trunk) 8dcf3c5793ff1a8a79dc94d268c91c2bf388894a
    Following parent with do_switch
    Successfully followed parent
    r7802 = 9bbd4194041675ca5c9c6f3917e05ca5654a8a1e (refs/remotes/newbranch)

git-svn did all the work and now knows about the remote:

    # git show-ref | grep newbranch
    2df23af4733f36f5ad3c14cc1fa582ceeb3edb5c refs/remotes/newbranch

Step 3: Create your new local branch tracking the remote one:

    # git checkout -b git-newbranch -t newbranch
    Checking out files: 100% (413/413), done.
    Branch git-newbranch set up to track local ref refs/remotes/newbranch.
    Switched to a new branch 'git-newbranch'
Comment: Following this **finally** allowed me to understand (`show-ref` is invaluable)! For anyone stuck with wrongly referencing remote branches, you can delete them (I had to do `git branch -d newbranch` and then force remove the ref dir in `.git/svn/refs/remotes/newbranch`) and then start over at step 2 (above).
Answer: I have not found any documentation about this feature, but looks like git svn configuration supports multiple fetch entries. This way you can also add branches separately without need to add another remote svn repository entry to your config nor using wildcards to get all branches of certain directory.
Assume that your SVN tree is really nasty having lots of branches without any logic how they are located, e.g. having branches and sub-directories containing more branched.
i.e.
trunk
branches
  -> branch1
  -> sub-dir1
    -> branch2
    -> branch3
  -> sub-dir2
    -> branch4
    -> sub-dir3
      -> branchX
<... hundreds more ...>

and you just want to hand pick some of the branches to be included to your git repository.
You may first init your repository with only trunk without any additional branches:
git svn clone -r 10000:HEAD https://svn.com/MyRepo myrepo --prefix=svn/ --trunk=trunk

After that you should see following configuration:
localhost: elhigu$ git config --get-regexp "svn-remote."
svn-remote.svn.url https://svn.com/MyRepo
svn-remote.svn.fetch trunk:refs/remotes/svn/trunk

when ever you want to fetch new branch from MyRepo you can just add new fetch entries to configuration by:
git config --add svn-remote.svn.fetch branches/sub-dir2/branch4:refs/remotes/svn/branches/sub-dir2/branch4

Or you may edit the same configuration in .git/config
To fetch the new branches after adding them to config just run:
git svn fetch -r 10000:HEAD

[Edit] Sometimes it seems to be necessary to run fetch with --all parameter to fetch newly added branches:
git svn fetch --all -r 10000:HEAD

Answer: Instead of dealing with the git-svn quirks you may try SubGit.
One has to install SubGit into Subversion repository. After that one can use standard git workflow instead of using special git-svn commands:

Pushing new commits:
git-svn:
$ git commit
$ git svn rebase
$ git svn dcommit

SubGit:
$ git commit
$ git push

Fetching incoming changes
git-svn:
$ git svn rebase

SubGit:
$ git pull [--rebase]

Creating a new branch:
git-svn:
$ git svn branch foo
$ git checkout -b foo -t remotes/foo
$ git commit
$ git svn dcommit

SubGit:
$ git checkout -b foo
$ git commit
$ git push

See SubGit documentation for more details.
Comment: SubGit has the disadvantage that it creates two repositories - one svn, and one "shadow" git repository. This might be a problem for huge SVN repositories...
Comment: @Udo -- any company not willing to buy their repository server a hard drive has their priorities messed up.

But most places with huge repositories take their repositories pretty seriously, and the disk space requirements for repositories are generally not a major issue, even for companies with decades of history and tens of millions of lines of code and hundreds of thousands of revisions.

It's the company's most concrete form of their core intellectual assets, and disk space is pretty inexpensive.

It might trigger a need to upgrade a RAID controller, but even so, the gain in productivity...
Comment: @Udo if SVN repository has a few projects, one may specify just one of them and synchronize it with Git repository. In this case there's no need to convert the whole Subversion repository into Git. But if one has a huge SVN project in this repository, one may convert not the whole history of this repository but the history starting from some minimal revision. This allows to decrease the size of translated Git repository.
Comment: @Bob Kerns - The point is that "size wise" SVN and Git and not compatible. It's not a question of disk storage or so. But you can work with a huge SVN repository because usually you need to checkout out only a few files/projects. But you can't clone a huge Git repository - it doesn't make fun at least ;-)
By "huge" I mean several Gigs.
Answer: To add to vjangus' answer, which helped me, I also found it useful to add use git grafts to tie the branches to the trunk at the appropriate point - allowing git to see the history and perform merges correctly.
This is simply a case of adding a line to .git/info/grafts with the hashes:
<initial branch commit> <parent commit in trunk>

eg.
378b0ae0902f5c2d2ba230c429a47698810532e5 6c7144991381ce347d4e563e9912465700be0638

Credit to http://evan-tech.livejournal.com/255341.html
(I'd add this as a comment, but I've not enough reputation.)
Answer: If you don't check out with a valid layout, you won't be able to checkout a remote branch.
This is what I do:
git svn init -s <svn path with no trunk> local_repo
cd local_repo
git svn fetch
## wait

After that, you can switch to a remote branch:
git checkout --track -b branch_name branch_name

Then you will automatically be switched to your branch.


Como chamar um método para dentro de um If e Else?

Question: Estou desenvolvendo um software para uma videolocadora com design pattern MVC (Model-view-controller) e está ocorrendo o problema de não chamar o método salvar() e o metodo alterar() para dentro do If e Else no botão Salvar. Se a variavel tipocadastro for "novo" ele salva e se a variavel tipocadastro for "alteração" ele altera. Já tentei varias formas e não consegui encontra a solução..e alguém aí poderia me ajudar ? Desde já, agradeço!
Classe VideoPessoa, da camada view:
public class VideoPessoa extends javax.swing.JFrame {

    PessoaController pessoaController;
    Pessoa pessoa;
    String tipoCadastro;

    /**
     * Creates new form Pessoa
     */
    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
        this.carregarPessoas();// Fica sublinhado em vermelho indicando erro!
         this.novaPessoa();// Fica sublinhado em vermelho indicando erro!
        this.habilitarCampos();// Fica sublinhado em vermelho indicando erro!
    }

Botão de salvar e o botão de alterar, dentro da camada view:
       private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
                    // TODO add your handling code here:

                    if (tipoCadastro.equals("novo")){
                        salvarPessoa();// Fica sublinhado vermelho indicando erro!

                    } else if(tipoCadastro.equals("alteracao")){

                        alteraPessoa(); // Fica sublinhado vermelho indicando erro!
                  }
            }
        }

     private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {
                    // TODO add your handling code here:
                    novaPessoa();
                    habilitarCampos();
                    recuperarPessoas();
                    tipoCadastro = "alteracao";
                }
         private void novaPessoa(){
                habilitarCampos();

                txtCodigo.setText("Novo");
                txtNome.setText("");
                txtEndereco.setText("");
                txtBairro.setText("");
                txtCidade.setText("");
                txtCPF.setText("");
                txtUF.setText("");
                txtTelefone.setText("");
                txtCelular.setText("");
                txtSexo.setText("");
                tipoCadastro = "novo";
            }

 public boolean alterarPessoa() {
        pessoa.setCodigo( Integer.parseInt(this.txtCodigo.getText()));
        pessoa.setNome(this.txtNome.getText());
        pessoa.setEndereco(this.txtEndereco.getText());
        pessoa.setBairro(this.txtBairro.getText());
        pessoa.setCPF(this.txtCPF.getText());
        pessoa.setSexo(this.txtSexo.getText());
        pessoa.setUf(this.txtUF.getText());
        pessoa.setCelular(this.txtCelular.getText());
        pessoa.setTelefone(this.txtTelefone.getText());
        pessoa.setCidade(this.txtCidade.getText());

// Aqui executo um teste se altera e quando exibe esse teste os dados não ficam alteradose e sempre exibe a mensagem alterados com sucesso!

          Integer codigo = pessoa.getCodigo();
         String nome = pessoa.getNome();
JOptionPane.showMessageDialog(this, "Código:"+codigo+ "nome:"+nome);

        if (pessoaController.alterar(pessoa)) {

            JOptionPane.showMessageDialog(this, "Registro alterado com sucesso!");
             this.desabilitarCampos();
            this.carregarPessoas();
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "Erro ao alterar os dados!", "ERRO", JOptionPane.ERROR_MESSAGE);
          return false;
        }

    }

Comment: Qual erro indica sublinhado?
Comment: @rray Esse erro : `cannot find symbol `
Comment: Oi, uma vez eu li que em java o equals compara tipo de dados e não o valor que esta dentro da variável, tente mudar a comparação para == Exemplo: tipoCadastro == "novo", Verifica se funciona assim.
Comment: Esse seu método salvarPessoa(); vem da onde?
Comment: @Techies  De dentro da camada view e mesmo assim não chama o metodo salvar() e nem alterar(), por que?
Comment: Ele não chama ou está dando erro? Pois no comentário você diz que está com erro
Comment: Ele não chama e fica sublinhado de vermelho indicando que alguma coisa esta errada e quando passo o ponteiro do mouse em cima, ele exibe a mensagem: `cannot find symbo`!
Comment: Pelo que notei tem uma `}` a mais no seu método
Comment: @Techies Eu tirei essa aspa e chamo os métodos sem essa aspa..4 dias inteiros perdidos só por causa de uma aspa!
Comment: @Techies Valeu e nem mesmo assim altera os dados da minha pessoa..
Comment: Posta seu método alterar que eu tento ajudar
Comment: @Techies Atualizei minha pergunta..
Comment: Quando voce clica em alterar os campos da pessoa estão preenchidos?
Comment: Quando clico sim por que coloco palavras para mim altera.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/31199/discussion-between-techies-and-igor-contini).
Comment: if (salvarPessoa()){ // faça alguma coisa } if (alterarPessoa()){ // faça alguma coisa } Não entendi muito bem sua pergunta, mas seria isso?
Answer: Bom, a priori vejo que toda vez que você aciona o botão de Alterar Pessoa, você chama antes o novaPessoa(), que, no caso, limpa todos os campos e nao alteraria seu objeto. Então não o chame antes de alterar a pessoa.
Outro detalhe que, nesse caso, é melhor utilizar um booleano, que ocupa menos memoria que uma String e não há problemas de comparação (uma String em upperCase é diferente de uma String em lowerCase).
Ficando algo dessa forma:
public class BlaBlaBla {
    boolean alterarPessoa = false;

  private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {
     habilitarCampos();
     recuperarPessoas();
     alterarPessoa = true;
  }

  private void novaPessoa(){
   habilitarCampos();

   txtCodigo.setText("Novo");
   txtNome.setText("");
   txtEndereco.setText("");
   txtBairro.setText("");
   txtCidade.setText("");
   txtCPF.setText("");
   txtUF.setText("");
   txtTelefone.setText("");
   txtCelular.setText("");
   txtSexo.setText("");
   alterarPessoa = false;
 }

  private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
          if (!alterarPessoa){
              salvarPessoa();
          } else {
              alteraPessoa();
          }
    }
}

Comment: Acabei de achar em um outro forum um problema igual ao meu! To fazendo reaproveitamento de código, ou seja, ctrl+c e ctrl+v de um colega meu, mas eu não sabia que ele tinha copiado o código dele na internet e achei o código que ele tinha copiado. Além disso eu não sabia que meu colega tinha copiado um trecho de um código de um outro forúm eai o dono do código estava encontrando o mesmo problema do que eu que é de não altera os dados da minha pessoa..e nem achei a solução..Segue o link : [http://www.guj.com.br/java/253029-update-de-registros-no-banco-de-dados-mysql-nao-realiza-a-alteracao]
Comment: Entendi, é bom sempre procurar na internet pontos específicos de ajuda, códigos completos costumam ser cheios de problemas. Quando somos iniciantes, é comum que nao saibamos julgar um código em uma linguagem que não dominamos, daí para cair em codigos com más práticas, más implementações e futuros problemas, é muito simples. Basta um Copiar/Colar. Espero que a resposta te ajude a entender um pouco mais e a corrigir o problema. Boas implementações!
Comment: Valeu cara! Pelos menos achei a resposta e vou implementar meu código e fazer as devidas correições necessárias a partir da sua resposta e da outra resposta do outro fórum!


Let $\langle a_n\rangle$ be a sequence where $a_n = {\sum\limits_{j=1}^{n}(-1)^j2/n}$ then

Question:
Let $\langle a_n\rangle$ be a sequence where $a_n = \sum\limits_{j=1}^{n}(-1)^j2/n$

is oscillatory

diverges to $+\infty$

diverges to $-\infty$

converges to $0$

I think by taking subsequences $\langle a_{2n}\rangle =(2/n) +(2/n) +\ldots +(2/n)$ ($n$-times) ${}= 2$ and $\langle a_{2n-1}\rangle = -2/n -2/n -\ldots -2/n$ ($n$-times) ${}=-2$ which is cunverging to $2$ and $-2$ respectively. So that the sequence is oscillatory. I have doubt taking this type of subsequence is right or wrong.
Answer: The correct answer is 4). Write down the sums $\sum\limits_{k=1}^{n} (-1)^{k}$ and convince yourself that these are bounded. So if you multiply these by $\frac 2n $ and let $n \to \infty$ you get $0$.
Answer: We have $a_n=\frac{2}{n}\sum_{j=1}^n(-1)^j=\frac{1}{n} \cdot (1-(-1)^{n+1})$ and
$|a_n| \le 2/n.$ for all $n$
Can you proceed ?
Comment: this means $-2/n{\leq }a_n{\leq}2/n$ then by sandwitch theorem $ converges to 0
Answer: 1)$a_n= (-2/n)$, $n$ is odd.
2) $a_n=0$, $n$ is even.
1')$\lim_{ k \rightarrow \infty } a_{2k+1} =0$, $k=0,1,2,..;$
2')$ \lim_{l \rightarrow \infty} a_{2l}=0, l=1,2,3,...;$
Lemma:
The $2$ subsequences $a_{2l}, a_{2k+1}$,
$l=1,2,..,$ $k=0,1,2,..,$
converge to $0$, hence $a_{n}$ converges to $0$.
Can you prove the Lemma?
Answer: $$a_n {= {\sum\limits_{j=1}^{n}(-1)^j2/n}\\\to a_{2k}=0\\,\\a_{2k+1}=-{2\over 2k+1}}$$then this sequence oscillatorily converges to 0.


Binary variance? Comparing two sacks of uneven coins or two heterogenous groups of people

Question: I have two sacks of coins. In one sack, the coins are all uniform, each giving a fairly constant 0.5 chance of heads (based on tossing a few of them and also visual inspection). I then estimate the binary variance from the 0.5 success rate. The variance tells me how much I can expect the average success rate in samples to vary due to chance when I sample again and again.
In the other sack, the coins are all bent, uneven. I try a few coins. Some are heavily biased one way, others the other way. Nonetheless, I toss 100 of them in sequence, 1 toss each. The average turns out to be 0.5. Based on that, the estimated binary variance is the same as the sack of uniform coins.
Should we not incorporate our knowledge that a lot of the coins in that sack are heavily biased? Wouldn't we expect a wider margin of error for sampled averages from that sack? Or is it that the average probabilities very quickly average out and we can treat the coins as uniform?
Context for this question: If we are comparing two groups of people on a binary decision task, does it matter that there is a lot of known individual variation between individuals in one or both groups?
I tried doing a simulation where each group was comprised of different sub-populations, each having their own probability of acting a certain way. It didn't seem to make any difference when their behavior was averaged out. Somehow, I was expecting samples of heterogeneous individuals to vary more than samples of homogenous individuals, even when the average behavior is approximately the same in both.
Answer: Lets take your example to it's most extreme conclusion and imagine an infinite sack of rigged coins that each magically give a result of either 100% heads or 100% tails.
As long as the chance of drawing one of these perfectly rigged coins is 50/50, we draw a new coin each flip and we have no knowledge of if the coin is rigged or not before drawing, the results in both variance and expected value over time will behave in an identical way to fair coins being flipped over and over again despite the coins being individually completely biased.


Ruby error with simple ActiveRecord.find

Question: I'm writing some rake taks to find objects with a simple find method as follows:
skill = Mastery.find(:first, :conditions =>  [ "tree = ? AND tier = ? AND column = ?",
              i.to_s,
              row_index.to_s,
              col_index.to_s
            ])

This works fine locally. However, when I deploy to my production environment the server fails and responds with this error:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'column = '1') LIMIT 1' at line 1: SELECT  `masteries`.* FROM `masteries`  WHERE (tree = '1' AND tier = '1' AND column = '1') LIMIT 1

I'm using the mysql2 gem in my rails app. Any idea what I can do to fix this?
Comment: Are you using sqlite in development?
Answer: Is it possible that "column" is a reserved word on that particular version of MySQL?
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
It could be the case that MySQL is giving an error because you're using a reserved word as a column name.
Comment: Ah, interesting thought. I'll give it a shot!


Integral $\int_{0}^{1}\frac{\sin{x}}{x}\operatorname d\!x$

Question: In  this problem $$\int\limits_{x=0}^{x=1}\frac{\sin{x}}{x}\operatorname d\!x$$
 using Taylor series I got   $\sum_{0}^{\infty} $$\frac{(-1)^n}{(2n+1)!(2n+1)} $ then what to do? Is it the final answer?
Comment: Nothing else to do (at leat to me). Your result is correct and you cannot do much more. The exact result is $\text{Si}(1)$ which is not rational (approximately 0.946083).
Answer: I think this integration have not an analytical form. The Sine Integral
\begin{equation}
\mathrm{Si}(x)=\int_0^x\frac{\sin(t)}{t}dt
\end{equation}
have a property that $\lim_{x\rightarrow+\infty}\mathrm{Si}(x)=\frac{\pi}{2}$. And this result is given by using integral with parameters:
\begin{equation}
I(\alpha)=\int_0^x\frac{\sin(t)}{t}e^{-\alpha t}dt
\end{equation}
You can find the deduction in references about calculus.
So the result you want to compute, say $\mathrm{Si}(1)$, have not a analytical solution. The series you talk about is obviously convergence but can not be computed analytically.
Comment: alright. thanks a lot
Answer: Well, that depends on the question. You can tell if this alternating series converges by calculating $\lim_{n \to \infty} a_n$, where $a_n = \frac{1}{(2n+1)!(2n+1)}$.
An alternating series is convergent iff such limit is equal to zero.
Comment: lol, I meant question..
Comment: sorry I couldn't understand
Comment: I meant "depends on the 'question'" not 'answer' in my answer above.. And yes, I would say so. There are some criteria for the error we get using only finite number of elements of the series. But I am not sure if we can apply here, that if we count only $a_1 + a_2 + \cdots a_n, n \in \mathbb{N}$ then the error is less then $a_{n+1}$. Personally I think it is wrong.
Answer: http://www.wolframalpha.com/input/?i=int%28sin%28x%29%2Fx%29dx+from+0++to+1
where
Sine Integral-http://mathworld.wolfram.com/SineIntegral.html
just use free software to approximate such integrals which could not be represented by elementary function form


Azure SSO login with ApplicationId and Tenant Id not returning successful claim output

Question: public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app) {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions() {
            CookieDomain = ".xxx.com"
        });

        var notifications = new OpenIdConnectAuthenticationNotifications {
            AuthenticationFailed = OnAuthenticationFailed
        };
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions {
                ClientId = SystemSettings.ClientId, //This is the client Id of the central Multi-tenant Azure AD application
                    Authority = SystemSettings.Authority,
                PostLogoutRedirectUri = SystemSettings.PostLogoutRedirectUri,
                Notifications = notifications,
                //ProtocolValidator = new OpenIdConnectProtocolValidator() { RequireNonce = false},
                UseTokenLifetime = false,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() {
                    ValidIssuers = SystemSettings.ValidIssuers
                }
            });
        }
    }

For SSO login we are calling OWIN context:
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = string.IsNullOrWhiteSpace(returnUrl) ? "/account/authenticated" : string.Format("/account/authenticated?companyCode={0}&returnUrl={1}", companyCode, HttpUtility.UrlEncode(returnUrl)) },
                            OpenIdConnectAuthenticationDefaults.AuthenticationType);
                    return null;

After SSO succesfully login, I am redirecting to below route details:
[Route("account/authenticated")]
[AllowAnonymous]
public ActionResult Authenticated(string returnUrl, string companyCode) {
       FileLogger.Log($"System.Web.HttpContext.Current.Request.IsAuthenticated: {System.Web.HttpContext.Current.Request.IsAuthenticated}");
        var identity = (ClaimsIdentity)Thread.CurrentPrincipal.Identity;
        var claims = JsonConvert.SerializeObject(identity?.Claims?.ToList(), new JsonSerializerSettings() {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        });
        FileLogger.Log($"claims: {claims}");
        if (System.Web.HttpContext.Current.Request.IsAuthenticated) {
            var token = AuthorizationService.AuthorizeUser();
            FileLogger.Log($"AuthorizationService.AuthorizeUser() returns: {token}");
            if (!string.IsNullOrWhiteSpace(token)) {
                ViewBag.ClientCode = companyCode;
                ViewBag.Token = token;
                ViewBag.ReturnUrl = returnUrl;
                return View();
            }
            return null;
        }
        var currentClaimsPrincipal = ClaimsPrincipal.Current;
        if (currentClaimsPrincipal != null && currentClaimsPrincipal.Claims != null) {
            var myClaimsPrincipal = new ClaimsIdentity(currentClaimsPrincipal.Claims);
        }
        return null;
    }

But claim output is not coming and i am getting false authentication  and no claim:
Identity:
{System.Security.Principal.GenericIdentity}
    Actor: null
    AuthenticationType: ""
    BootstrapContext: null
    Claims: {System.Security.Claims.ClaimsIdentity.<get_Claims>d__51}
    CustomSerializationData: null
    IsAuthenticated: false
    Label: null
    Name: ""
    NameClaimType: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
    RoleClaimType: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"

Answer: As far as I knew, we can use the following code to get the claims after we complete Azure AD auth
var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
/*
 The token's claim "aud" is  the application's client ID. For more deatils, please refer to https://learn.microsoft.com/en-us/azure/architecture/multitenant-identity/claims.

*/
 foreach (var claim in userClaims.Claims) {

                // get app id
            }

            // TenantId is the unique Tenant Id - which represents an organization in Azure AD
            ViewBag.TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;

Answer: I solved it by updating OWIN packages and with below links:
https://dotnetcodetips.com/Tip/91/Azure-OWIN-website-login-gets-stuck-on-a-never-ending-redirect-loop.


Onion Architecture : Can UI depend on Domain

Question: I am making an ASP.NET MVC website with an Onion architecture. I have implemented a repository pattern and am now creating a Controller method in my project. This is my architecture:

Domain : Entities / Domain Interfaces
Repository : Generic repository (for now) using Entity Framework Code First
Service : Generic Service that calls the Repository
MVC

Now in my MVC project I need to access repository but according to Jeffrey Palermo, MVC is dependant from Service and Domain, but nothing is said of Repository.
Can i make my UI dependant of Repository?
I cannot do anything without the dependency right now, because Service creation depends on Repository. I have tried modifying Startup.cs to not directly use Repository objects in my Controllers, but it still means I need to add a reference to Repository (see http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/ )
Comment: At this point MVC (UI) is the composition root, which would need to know all the layers in order to register them with the DI container. Can you show some code to demonstrate what it is that is causing problems.
Comment: @Nkosi ok, so I thought there could be pbs with that but I guess not. Thanks alot!
Answer: At this point MVC (UI) is the composition root, which would need to know all the layers in order to register them with the DI container.
The start up would either refer to the implementations directly when registering them or indirectly via extension methods exposed from that layer. Either way the composition root needs to reference all lower layers if they are to be added to DI container.
The controllers should also be dependent on abstractions from lower layers and not concretions.
If injecting repositories directly into controllers then I suggest reviewing the design as that may indicate mixing of responsibilities.
Comment: Ok thanks! I just need Repos to pass them as parameters to instantiate Services, I will not access their methods from the controller (my service is in charge of this). So if I can do this in Startup, all is solved !


Vector calculations in Visual Studio C#

Question: I'm making a program that will tell you the angle of limbs when given a picture. So for example, you load a leg splits picture on the screen, you click on each joint, the program records the joints positions, then it gives you the angle between both legs let's say.
I am using Microsoft Visual Studio Express 2015, Windows 10.
I managed to do this on Unity 4.6, but I can't make the vector functions work now on Visual Studio. Basically I found this page:
https://msdn.microsoft.com/en-us/library/system.windows.vector.anglebetween(v=vs.110).aspx
... which gives you this method:
<code>private Double angleBetweenExample()
{
    Vector vector1 = new Vector(20, 30);
    Vector vector2 = new Vector(45, 70);
    Double angleBetween;

    // angleBetween is approximately equal to 0.9548
    angleBetween = Vector.AngleBetween(vector1, vector2);

    return angleBetween;

}
</code>
"Vector" doesn't seem to be a proper variable name, so I added using System.Windows.Vector; at the top.
This line gives an error, "Vector" is underlined in red. What am I missing?
Your help is appreciated, and please excuse this basic question, I'm just learning this stuff and I'm quite lost.
Comment: You need to make sure that `WindowsBase.dll` is referenced by your project.
Comment: Not exactly related to your question, but kind of relevant. Note that Visual Studio Express is a restricted version of Visual Studio. With Visual Studio 2015 you have the Community version which is also free, but similar to a conventional (fee-based) Visual Studio. PS: you might easily create your own vector class. Some of the in-built functions might not be so straightforward to be implemented, but perhaps you might not need them. For example: creating a function calculating the angle between two vectors is not too difficult and might be a good exercise.
Answer: Which .net framework are you using?
here https://msdn.microsoft.com/en-us/library/system.windows.vector.anglebetween(v=vs.110).aspxit
it is specified to work only for 4.5 & 4.6
Comment: Not true - "Available since 3.0". That page is just the 4.5/4.6 version there are other version of that page.
Comment: "You need to make sure that WindowsBase.dll is referenced by your project. – ChrisF"
This did it, it was very simple, I needed to add the reference and now it works. Thank you guys. I will now check how I have to edit this to display it is solved... can I give points or anything?

Vector calculations in Visual Studio C#


Import WordNet In NLTK

Question: I want to import wordnet dictionary but when i import Dictionary form wordnet i see this error :
 for l in open(WNSEARCHDIR+'/lexnames').readlines():
IOError: [Errno 2] No such file or directory: 'C:\\Program Files\\WordNet\\2.0\\dict/lexnames'

I install wordnet2.1 in this directory but i cant import
please help me to solve this problem
import nltk
from nltk import *
from nltk.corpus import wordnet
from wordnet import Dictionary

print '-----------------------------------------'
print Dictionary.length

Answer: The following works for me:
>>> nltk.download()
# Download window opens, fetch wordnet
>>> from nltk.corpus import wordnet as wn

Now I've a WordNetCorpusReader called wn. I don't know why you're looking for a Dictionary class, since there's no such class listed in the docs. The NLTK book, in section 2.5, explains what you can do with the nltk.corpus.wordnet module.
Comment: The version from @alvas worked for me using Jupyter notebook, python 3.5. `ntlk.download()` alone cannot open a GUI from inside a notebook. It sure would be nice if the help for this command did a better job of listing the correct strings to use for all the options.
Comment: Maybe there has been an update, but calling `ntlk.download()` in Jupyter opens the GUI on my Win10 computer. (Jupyter is running on localhost, and not on a remote host.)
Comment: Solved my problem.
Answer: You should try these commands:
import nltk
nltk.download('wordnet')

It worked for me.

Import WordNet In NLTK


cumulative distribution of transformed normal

Question: I am reading a paper, and in that it says if $P(x|y = +1) \sim N(\mu_1,\Sigma_1)$ and $P(x|y = -1) \sim N(\mu_{-1}, \Sigma_{-1})$.  Then if we take the classification $f(x) = a^Tx-b$, then the cumulative distribution $P(ax < b| y = +1) = \Phi(\frac {b-a^T\mu_1} {\sqrt(a^T\Sigma a)})$ where $\Phi$ is the cdf of standard normal distribution.  I know that $P(ax-b|y) = +1 \sim N(a\mu_1 -b, a^T\Sigma_1 a)$.  But how does the cumulative function get that form.
How come they get $b - a^T\mu_1$ in the numerator ?
Answer: The cdf itself is just the cdf of any gaussian, which has an integral form. You can follow this link for further information about it:
https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function
As you can see the cdf of a gaussian is this phi with "x-mu" in the numerator and "sigma" in the denominator.
Now because we'd like to evaluate the probability of axmu-b" as "mu" so the numerator is 0-(amu-b)=b-a*mu.
Someone, please edit my math, I'm not familiar with Latex :(
Answer: Given that the class conditional probability density functions are multivariate normal. We know that, if the random vector $x:p\times 1\sim N_{p}(\mu, \Sigma)$, then every linear combination of the components of $x$ is a univariate normal ransom variable. Let $a:p\times 1$ be a vector of constants. Then $a^{T}x\sim N_{1}(a^{T}\mu,a^{T}\Sigma a)$. Then, by definition,
\begin{eqnarray*}
P\left(a^{T}x < b|y=+1\right) &=&P\left(a^{T}x -a^{T}\mu < b - a^{T}\mu|y=+1\right)\\
&=&P\left(\frac{a^{T}(x-\mu)}{\sqrt{a^{T}\Sigma a}}<\frac{b - a^{T}\mu}{\sqrt{a^{T}\Sigma a}}|y=+1\right)\\
&=&\Phi\left(\frac{b - a^{T}\mu}{\sqrt{a^{T}\Sigma a}}|y=+1\right)
\end{eqnarray*}
In the first equation we subtract the mean of the random variable $a^{T}x$ and in the second equation, we divide on both sides by the standard deviation $\sqrt{a^{T}\Sigma a}$ of $a^{T}x$. The quantity $\frac{a^{T}(x-\mu)}{\sqrt{a^{T}\Sigma a}}$ is a standard normal variate, and hence, $\Phi()$.


k-means clustering with some known centers

Question: I am working on an project where I need to add clusters (likely double but I want it to be arbitrary) to an existing kmeans clustering solution.
I am actually only interested in the centers. So is there a method where I can add more clusters with the initial ones fixed? I guess the end result will not meet the exact definition of kmeans, but something as close as possible.
I would greatly prefer a python tool. Even better if sklearn. But I am open to alternatives if I have to be.
Thanks!
Comment: It really does matter to me — in this case I am more likely to read about this than to implement it — what is assumed known or fixed or given and what is estimated from the data. I would want to see some argument on why that makes sense.
Comment: Are you adding data too, or do you just want a finer classification of the same data with existing clusters kept? Doesn't sound at all standard or well posed....
Comment: @NickCox I think this could reasonably be interpreted as a constrained version of the standard k-means problem, in which case it wouldn't matter whether new and/or existing data is used.
Comment: @NickCox, I will be adding data. I have some centers that are fixed and I want to add more partitions without moving the already-fixed centers.
Answer: This is equivalent to a modified version of k-means, where some of the centroids are constrained to take given values. Below, I'll describe how to formulate this as an optimization problem, then how to solve it.
Formulating the problem
Let $X = \{x_1, \dots, x_n\}, x_i \in \mathbb{R}^d$ be a set of data points to cluster and let $\{c_1, \dots, c_k\}, c_i \in \mathbb{R}^d$ denote a set of $k$ centroids. Suppose the first $k' < k$ centroids are already known (e.g. they've been learned using an initial round of k-means clustering). $X$ may or may not include data used to learn this initial clustering.
The goal is to learn the remaining $k-k'$ centroids such that, when each point is assigned to the nearest centroid, the sum of squared point-to-centroid distances is minimized:
$$\min_{c_{k'+1}, \dots, c_k} \ \sum_{j=1}^k \sum_{x \in S_j} \| x - c_j\|^2$$
where $S_j$ is a set containing the points assigned to centroid $j$ (i.e. points for which $c_j$ is the nearest centroid using Euclidean distance). Note that the above is equivalent to the standard k-means problem, with the first $k'$ centroids constrained to take known values.
Solving the problem
The standard (unconstrained) k-means problem is typically solved using Lloyd's algorithm:

Initialize cluster centroids. For example, choose them to be a random subset of data points. More clever strategies exist as well (e.g. k-means++).

Repeat until assignment of points to centroids doesn't change:

Assign each point to the nearest centroid (using Euclidean distance).
Update each centroid to be the mean of all points assigned to it.

A simple modification of Lloyd's algorithm can be used to solve the modified k-means problem above: In steps 1 and 3, keep the first $k'$ centroids fixed at their given values, and only initialize/update centroids $k'+1$ through $k$
Notes

The solution to the modified k-means problem above will have error at least as large as standard k-means. That is, constraining the first $k'$ centroids can only reduce performance (or, at best, leave it unchanged) compared to re-solving for all $k$ centroids. Whether this is acceptable depends on the underlying problem you're trying to solve.
This is a non-standard problem. It's unlikely that a software implementation already exists, but it should be straightforward to implement it yourself.
Lloyd's algorithm may converge to a local minimum, so it gives only approximate solutions to the k-means problem. Finding an exact solution is NP-hard. A common strategy is to run multiple times from different initial centroids.
Various strategies for accelerating Lloyd's algorithm (e.g. using the triangle inequality to reduce the number of distance computations) should be applicable in the constrained case as well (see references here).
Answer: I'm not aware of any expansion of k-means cluster analysis that allows for clusters to be fixed in location, and to be perfectly frank it doesn't seem like a good idea. That being said it shouldn't be too difficult to code something like this up yourself.
Standard k-means (with a random partition initialization) works by the following algorithm.

Assign elements to clusters at random.
calculate new centers of each cluster.
assign elements to nearest cluster centroid
repeat 2-3 until no elements change cluster.

The only amendment you would need to make for your constraints is to never update the centroids of the clusters you want to remain fixed in location in step 2.
However, if that sounds like too much work and you are willing to accept small deviations from the original centroids, scikit learn seems to support weighting your data. You could try adding the centroids you wish to keep as additional data points with a very high weight.
Answer: A library won't do all the work for you.
But with just 4-5 lines of code you should be able to build a k-means variant that only updates those centers that you want to move and keeps the others fixed. That will work.


Automatic reference of class files inside App_Code vs reference of class files outside App_Code

Question: all questions refer to Web site projects.

1) Why are file classes inside App_Code folder automatically referenced by the rest of application, while file classes created outside App_Code aren't?

2) I don't know much about compilation, but why do we need to explicitly reference class files created outside App_Code? Because those files will be compiled into dlls created and named by programmer and as such VS doesn't know what the names of these dlls  and so can't automatically reference these dlls?
3) Files outside App_Code by default don't get automatically compiled? But why not?

thanx
Answer: Sounds to me like you are expecting Web Application behaviour from a Web Site "project".
In a Web site each ASPX/ASHX file (outside of the App_Code) is considered content.  At any point you may wish to simply publish a few of the files to the web site.  Hence compiling all them at once into a single assembly is not desirable.
With a Web Application you don't normally publish just a few files, you complete a phase of the application, compile it all together and then publish.
You seem to indicate you have "classes" declared outside of App_Code?  Where would they be if not in their own dll project?  If in a dll project then you need to create a project reference to in the Web Site properties.
Comment: You need to create a reference to dll because VS doesn't know what you will name dll containing this class or...?
Comment: May I ask another question - if I create (in code behind) another public class (besides the one from which page will derive) and if I set TypeName attribute of ObjectDataSource to this class, ODS for some reason won't find it
Comment: Perhaps you should include a simple example of what you mean in your question.
Answer: The App_Code folder is mainly used with Website projects whereas with Web Application Projects you would typically reference the library class. App_Code is supposed to work with the WAP model but I find that it often doesn't play nice.
You can read more about it here (check the reference links):
http://www.codersbarn.com/post/2008/06/01/ASPNET-Web-Site-versus-Web-Application-Project.aspx


Cannot make support bottomsheet not-hideable when in Expanded state

Question: I'm trying to make a bottomsheet using google support library. The goal is to have a sheet that:

Can be hidden programmatically only
Its height is calculated automatically
Is defined statically in xml

So far so good, simple stuff. There is also this promising isHideable() which defaults to false.
But the bottomsheet seems to ignore the isHideable when the sheet is set to STATE_EXPANDED (although its not going to cover the whole screen). The only way to make it unhideable is to set a peek height (which I don't want). Is there a way to have it expanded and not-hideable without setting the height manually (or via layout change triggers)
Here is the (super slim) code used:
Activity.java
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View bottomSheet = findViewById(R.id.bottomsheet);
        BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setHideable(false);
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:id="@+id/bottomsheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:behavior_hideable="false"
        app:layout_behavior="@string/bottom_sheet_behavior"
        android:background="@android:color/white">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:text=":) :) :)"/>
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

Behavior
Answer: The simplest but hackish way I've found so far:
    behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    bottomSheet.post(new Runnable() {
        @Override
        public void run() {
            behavior.setPeekHeight(bottomSheet.getHeight());
        }
    });

And of course when there is need to hide it firstly call setHideable(true).
This is just a workaround that might lead to weird behavior.


How to extend and strengthen low end of vocal range? (I need about a whole tone extra.)

Question: There are a bunch of songs that I'd like to sing that sit just under my vocal range (the low E of the guitar range, or the D under it). I can reach these notes with some effort, but it feels forced and the volume drops dramatically. What can I do to improve matters?
Some possibilities I'm aware of:

Warm up and practise. Yep, that'll do it I guess. I'm hoping for advice here that's more low-end specific though: particular exercises or techniques or whatever.
Get good and drunk the night before so I look and feel (and sing) my best. Seriously, this gives me exactly the range I want, the question is how to get it reliably (and without a hangover).

I'm an instrumentalist not a singer, and not really ready to put large amounts of effort (and practising time) into this project. Is it even realistic to hope for a whole tone's worth of range extension without applying myself seriously to the problem?
Comment: I can't tell you how pleased I am to see that throwing a load of beer at the problem has worked. Somehow, this makes up for the world's problems of 2016, just a bit.
Comment: I also wonder why drinking gives the extra low register.
Comment: @Gauthier I wonder if it has to do with dehydration?
Comment: I guess the drinking (and also early in the morning before you have talked too much) gives the extra low because your vocal cord is relaxed, and easier gets down to the low frequencies. Normally, your vocal cord is a bit tighter, and it is more difficult to relax it enough to get down.
Comment: I doubt it. Rather the shouting at the pub means the chords are slightly irritated and inflamed.
Comment: practice Ohm.... is a best option
Comment: Yawning relaxes the vocal chords, and drink Luke warm water to lubricate
Comment: I'll add a vote for the inflammation of the vocal cords doing it.  My voice drops from drinking alcohol, but not, AFAIK, from muscle relaxants.  Admittedly, I have vastly more experience singing while drinking than singing on muscle relaxants.  But that's my anecdata.
Answer: One technique I know helps is to lift our head just a bit and try to relax as you go down. This will open up your airways to the maximum and also leave more room for your vocal cords to vibrate freely (the lower frequencies requires larger movements of the vocal cords). Just be care to not raise your head too much; If you raise your head too much, the vocal chords will stretch, and you will get the opposite effect. You need to find a perfect balance here.
I'm not sure if this technique will give you a whole note more down (it will probably give you some improvement), but it will certainly improve the performance and strength of what you are already capable of. And sorry - to do it well, you need to practice...

Note:
In the other end, when you go up in the frequencies, lower your head so you chin gets closer to your chest. This will help you to be more accurate in hitting the right note when you go up.
Answer: If your looking for a quick fix, the only reliable one is to transpose the songs you want to sing. Even in areas with trained singers such as opera and broadway, the songs were written in keys comfortable for their first performers. Even today, some revivals of broadway shows may adjust particularly rangey songs up or down a small amount. As for anything in the popular realm (rock, pop, etc. anything with guitars…) transposing is easy, and extremely common. I've learned to play some songs with bands in 2 or 3 different keys, depending on the singer.
However if you're willing to give it some time and effort, do some vocalises (like the warmup 5-4-3-2-1 Monica Cellio mentioned above). There are a great number of these, and you can make them up yourself. When working on range, you especially want to make sure you're singing correct; relaxed and in a healthy manner. Too many people try to press and force the voice beyond what is comfortable for it.
You mentioned you're an instrumentalist, but another thing to keep in mind is that trained singers don't regularly sing at the edges of their range. Most singers know their highest and lowest notes, their highest and lowest reliable note, and neither will be regularly used (in most cases). For example, though I'm far from a trained singer, my highest note full voiced is tenor Bb. I can rarely ever get that high though, and it's not pretty. My Ab's are more reliable, but I would not sing that high solo; I'd transpose. G is the highest I'm comfortable singing in a solo song, however if the transposition is easy, I might take it down to F.
If I were putting more time and effort into singing (as I would do if I land a choral teaching job) I'm sure I could strengthen my voice up to the Ab to make everything more reliable, relaxed, and pleasant-sounding, however it's doubtful my overall range would increase by all that much.
Finally, I don't know how old you are, but the human voice doesn't fully mature until the late-20's or even early 30's, depending on your voice type, so don't push anything that's beyond your range right now.
Comment: This is a good answer.  In addition, range is limited by physiology and even with training and warming up, some low notes will not be singable for all singers.
Answer: Every choir I've ever been in has done the 1-2-3-4-5-4-2-1 warmup (sing on open vowels, go up half a step, iterate), but I found that I got some help on the low end when a director added descending runs to the lineup: 5-4-3-2-1, then down a half-step and repeat.  You'll produce sound in warmups below where you can sing, just as ascending runs get you above where you would actually sing, but over time these kinds of exercises can stretch the range.
This isn't a quick fix, though; you'll probably need to do it daily for several months.
Answer: I take a drink of water, or something to relax  my vocal chords. After, a  glass of water, I find the lowest note I can confortably hit, and  starting from that note, I make a "wah" sound (W-AW) and on that 'aw' vowel, make your voice drift down lower (about a semitone). Be sure not to push, and make sure you drink plenty of water and give your voice time to relax, before starting this exercise from a lower note. You're gunna want to do these in intervals of 5. Do this about 5 times (say 'wah' 25 times) before relaxing, and moving to a lower note. Hope this helps!
Answer: The muscles in your larynx that are most dominant on low notes are the Thyroarytenoid muscles, it's the muscles that are responsible for shortening your vocal cords and make them thicker.
Just like any workout you do to muscles in your body, your muscles become stronger when you work them out and then stretch them.  Just working out on muscles isn't going to be enough, and infact it's going to shorten your muscles until they eventually become too tight.
That's why stretching is very important, and in the case of the Thyroarytenoid muscles - because the vocal folds are part of this muscles (they are directly attached to one side of it), it means that going for high pitches provides a great stretch to these muscles.
So in order to get more low notes, you will need to practice low notes and then stretch to high notes, and in fact this may sound odd but the higher notes you can reach comfortably (without pushing or straining!) will actually directy impact your lower ranges as well.
So practice the low notes using one or more of the ways people offered you here, but don't forget to stretch (high notes) afterwards if you want to realy develope these muscles effectively.
Hope this helped!
Answer: Try singing to the actual song on YouTube when you're beginning then try alone. It helps rather than singing acapella from the start. But seriously, you DO need to warm up, your voice will sound croaky otherwise.
Answer: Personally, I'm working on my lower range myself, and what I find works best in terms of long term development is when you're relaxed (whether that by drinking a warm, not hot, drink, getting a bit of a buzz from some alcoholic drink, or something like that) doing a 5 4 3 2 1 on an open vowel (ah, oh, and oo work well, I find).  I also find singing after a nap gives me a wider range, again because of relaxation.  The biggest thing whether for long term voice development or short term getting that slow note is relaxation.  Relax down into the new note, don't force it down, and try not to let the larynx drop, cuz that doesn't help and puts pressure on the voice that cuts off the range.
Answer: To extend your lower register, try to relax your thread open.  Let the sound resonate in that big tub.  To add resonance, let your jaw drop (pulling down your chin with your fingers may help in the beginning).  You can also try to expand this area by using what we call the bullfrog effect.  Good luck!
Comment: Dropping the jaw is important on both ends of the range as it opens the mouth and changes the acoustic impedance between the pharynx and the mouth.
Comment: What "thread"? What "tub"?


Modulos em Python linux

Question: Estou tendo alguns problemas para instalar módulos no meu python em linux. Atualmente estou usando o python 2.7.10, a maioria dos módulos eu utilizo o pip para instalar, porém quando eu executo o python 2.7.10 e importo meu modulo ele diz que não encontrou, porém se eu utilizar a versão 2.7.6 (/usr/bin/python2.7) eles funcionam, parece que quando eu instalo esses módulos ficam visíveis apenas para versão anterior.
Antes da 2.7.10 eu estava com a 2.7.9 e acontecia o mesmo problema.
Alguém sabe o que pode ser ?
Comment: Acho que o que está ocorrendo é que o `pip` que está sendo utilizado está carregando o Python errado, possivelmente `/usr/bin/python` que deve ser um symlink para a versão antiga. Use `ls -l /usr/bin/python` para ver se é realmente isso. Se for basta você refazer o symlink para o seu Python novo.
Answer: Você provavelmente tem duas instalações do Python — a 2.7.6 deve ser a que veio com a sua distribuição do Linux, e a 2.7.10, que eu imagino que você instalou à mão, em algum canto tipo /usr/local/?
Você pode usar o virtualenv pra gerenciar as várias instalações — é o método ideal, na realidade — mas se você quiser fazer algo porco, é só você usar
/usr/local/bin/python2.7 -m pip

ao invés de pip sempre que você for instalar um pacote; isso vai garantir que ele vai ser instalado no python 2.7.10, não no python 2.7.6.
Comment: Eu não encontrei nada no local, provavelmente eu tenha lá outra versão sim, mas não teria uma forma de excluir a versão 2.6 e deixar como default do meu sistema a 2.7.10 ?
Comment: Aparentemente a resposta é ["sim"](https://renoirboulanger.com/blog/2015/04/upgrade-python-2-7-9-ubuntu-14-04-lts-making-deb-package/), mas envolve um certo trabalho (e eu faria um backup das suas coisas importantes antes de tentar).
Comment: +1 para o uso de Virtualenv. A menos que você esteja configurando um servidor dedicado, o mais simples de se fazer e manter é utilizar Virtualenv.
Answer: S e o seu sistema veio com Python 2.7, é possível mante-lo com Python 2.7.10.  e o seu sistema veio com Python 2.6, não dá para mudar o Python padrãodo sistema para 2.7: você vai destruir seu sistema - a maioria das distribuições Linux tem vários programas chave para administração que dependem fortemente do Python no sistema.
A maneira correta de proceder é: usar o gerenciador do sistem apra baixar os pré-requisitos para compilar o Python  (por exemplo, em Debian, Ubuntu e derivados: "apt-get build-dep python-2.7", em fedora: yum-builddep python2). -Baixe o código fonte (o arquivo .tar.gz) de Python.org, e compile uma versão local, para o usuário - configure o prefixo para ser dentro de seu próprio Home (./configure --prefix=/home/usuario/usr) ou um prefixo de sistema, separado do /usr - /opt é uma boa pedida. A vantagem de usar um prefixo dentro do seu /home é não precisar em nenhum momento de permissões de super-usuário (sudo) para instalar a nova versão do Python.
Daí, instale o pacote virtualenv no Python do sistema, e para cada projeto em que for trabalhar, crie um virtualenv, usando o Python que voce compilou - para isso use o argumento -p do virtualenv.
Cada vez que for trabalhar no projeto, ative o virtualenv. A sequência, depois de compilado o Python novo, é essa:
apt-get install python-virtualenv
virtualenv -p /home/usuario/usr/bin/python-2.7 meuprojeto
cd meuprojeto
source bin/activate

e a partir daí coloque os .py do seu novo projeto dentro da pasta  - e instale outros módulos a vontade com o comando pip:
os módulos instalados estarão restritos ao virtualenv. Um segundo projeto que use versões diferentes dos mesmos módulos pode ser criado em outra pasta, e um projeto não vai interferir no outro.
(O passo source bin/activate deve ser executado em cada shell que você for executar programas de Python desse projeto - há pacotes auxiliares do virtualenv que permitem um comando mais simples para ativar os virtualenvs,  mas a diferença é quase que só cosmética)
Essa receita funciona da mesmíssima forma para versões mais recentes de Python - e você pode inclusive ter virtualenvs separados com Python 3.4 e Python 3.5 beta.

Modulos em Python linux


How to get css , javascript of a html element in a website

Question: I saw a slider in a website and I want to get the CSS and javascript of that element so I can use in my website. How can I accomplish that?
Comment: What's about the [inspector](https://developers.google.com/web/tools/chrome-devtools/css) in the dev-tools?
Answer: To read and use code from a website, you use an "Inspect Editor" which is integrated in the browser. An example of Firefox Inspect Editor:
https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector
There you can call up the HTML Editor and the Style Editor.


Webform views - creating a filter using date from user-submitted data

Question: We have a job submissions webform. In the form, there is a "closing date" field with a calendar picker (yyyymmdd format). When the closing date passes, the submission should be removed from view.

I created a relationship for the Submission Data: Expiry Date field so it can be used as a Filter.

Now that I have the data available as a filter, this is where I get stuck; I need the view to filter out the submission if the Expiry Date has passed. How can I do this?
Answer: I just found a patch for this exact functionality. Out of the box, you are right, it acts as its a straight up text field. If you were to use entityform instead of webform, I believe you would be able to do this as it uses normal drupal fields.
https://www.drupal.org/node/2527608
Answer: *Set the operator to 'is greater than'
*Select  'An offset from the current time such as "+1 day" or "-2 hours -30 minutes"'
*Set the value as "now"
Comment: Hi Bianca, thanks for the quick reply. Unfortunately, these values are only available to "date" fields -- for whatever reason, Drupal is not detecting this field as a date field (I suspect it is because it is user-submitted data) so these options are not available to me.


Linked List Assistance

Question: I'm working on a linked list in C with insert and print functions. However, I am getting a segmentation fault from the insert, and when I try to fix this I end up with one from the print function. Any help would be greatly appreciated.
    typedef struct node
    {
        struct node *next;
        double value;
    } NodeT, *NodeTP;

    int listSize = 0;

    int insert(NodeT *firstEle, int value)
    {
        NodeTP temp;

        if((temp = (NodeTP)malloc(sizeof(NodeT))) == NULL)
        {
            return 0;
        }

        // first node in the list.
        if(listSize == 0)
        {
            firstEle->value = value;
            firstEle->next = NULL;
        }
        // finds the end node and adds the new node to the list.
        else
        {
            while(temp != NULL)
            {
                temp = temp->next;
            }

            temp->value = value;
            temp->next = firstEle;
            firstEle = temp;
        }

        listSize++;
        return 1;
    }

    int print(NodeT List)
    {
        printf("Element: %.2f\n", List.value);
        return 1;
    }

    int main(int argc, char* argv[])
    {
        // creates the list.
        NodeTP list;

        if((list = (NodeTP)malloc(sizeof(NodeT))) == NULL)
        {
            return 0;
        }

        list = NULL;

        insert(list, 5);

        print(list[0]);

        insert(list, 15);

        print(list[1]);

        return EXIT_SUCCESS;
    }

Comment: Why do you set list to NULL right after the malloc?
Comment: This question appears to be off-topic because it is about yet another linked-list with NO APRRENT ATTEMPT AT DEBUGGING.
Comment: I will agree @Martin. I gave suggestions for fixing and not exact code fixes for that reason.
Answer: Print Issue
When it comes to the print statements, you are using an invalid syntax. You created a single pointer and allocated enough memory for that pointer and what it points to. You did not create an array of NodeT elements. As such, the list[x] will not work.
You will need to generate a function that will locate the 'x' element in the list you are making. You could include that in the print function you write. Just change it up to take the int of the element you want:
int print(NodeT head, int element) {}

Don't forget to check your bounds in case the element asked for is outside of your current range.
All you really need to do then is step through the elements to the desired one.
Insert Issue
In your if/else statement, why are you trying to iterate through 'temp'? 'temp' was created in this function and should have no other elements attached to it. You should be iterating through 'firstEle'. You also don't want to set firstEle = temp; as that will over write what was there before and you are now pointing to something else.
One way to simplify this code is to use a head and tail. The head never changes but the tail moves as elements get added. You can have 'insert' return the tail and when you insert a new element, just provide the tail and the new element will be added there, no iteration needed.
Memory Issue
While this will not be major for this program, I would adjust where I malloc my new node till after I have insured that it isn't the first element. Else, you have a block allocated that is never used. Or, if this is the first element to be added, free the block.
And Fred makes a good point. That will cause issues.
Answer: Multiple issues (the list is far from complete):

You're missing the include files for malloc() and printf().
You allocate memory in main(), but don't use it.
If you want to modify the list head in insert(), you have to pass a pointer to it.
You check if the memory allocation in insert() succeeds, but don't handle the case that it doesn't  - so you can as well just get rid of it.
As you ignore the return values of both insert() and print() you could as well change their return types to void.
While searching for the last element of the list, you overwrite the pointer (temp) to the memory you just allocated.
When you think you've found the last element, you actually make the new element's next point to it and set the first element to point to the new element, which would make it effectively the first and not the last element (if all the other stuff would work...).
You're trying to use array style access with [] for the list. You have to use pointers.

This is a version where I fixed at least the most basic errors in order to make it compile and at least work. It's still far from perfect (or even acceptable), but I tried change as little as possible to make it easier for you to spot the differences and learn what you did wrong and further improve it from there.
#include <stdlib.h>
#include <stdio.h>

typedef struct node
{
    struct node *next;
    double value;
} NodeT, *NodeTP;

int listSize = 0;

int insert(NodeT **firstEle, int value)
{
    NodeTP temp, lastEle;

    temp = (NodeTP)malloc(sizeof(NodeT));

    // first node in the list.
    if(listSize == 0)
    {
        temp->value = value;
        temp->next = NULL;
        *firstEle = temp;
    }
    // finds the end node and adds the new node to the list.
    else
    {
        for (lastEle = *firstEle;lastEle->next != NULL;lastEle = lastEle->next);

        temp->value = value;
        temp->next = NULL;
        lastEle->next = temp;
    }

    listSize++;
    return 1;
}

int print(NodeT List)
{
    printf("Element: %.2f\n", List.value);
    return 1;
}

int main(int argc, char* argv[])
{
    // creates the list.
    NodeTP list;

    list = NULL;

    insert(&list, 5);

    print(*list);

    insert(&list, 15);

    print(*list->next);

    return EXIT_SUCCESS;
}

Linked List Assistance


How do I hide buttons like the "delete" one in a node form?

Question: Consider I created a CCK node called assignment, and I am adding assignments with that.
There is a field called "published" with a check box. If the assignment is published, then it should not be deleted.
My problem is how I can hide the "delete" button if the assignment is published. By using prefix and suffix and using display: none; in hook_form_alter() will work, but it is not the secured way. I need something in the Drupal way.
Answer: You can use hook_access().
Super simple example will hide button "Delete" automaticaly and disallow deletion of some nodes in any other places in Drupal.
Important note:

The administrative account (user ID #1) always passes any access check, so this hook is not called in that case.

function MYMODULE_access($op, $node, $account) {
   if ($op == 'delete') {
      if ($node->something != 'something') {
          return FALSE;
      }
   }
}

For Drupal 7 there is hook_node_access() for this stuff.
Answer: We can use the below to hide the buttons in form alter.

unset($form['buttons']['delete']);
Comment: In this way it can be possible to delete content in Content Overview Page.
Comment: But the delete button is hide and what is the possible case to delete the content in the overview page. Your suggestion confused me :(
Comment: Removing a form field in that way is never the suggested way.
Answer: In Drupal 7 each content type has a permission (on the permissions page at yourdomain.com/admin/people/permissions) called "Delete own content" which you can use as long as the user isn't an administrator because admins have all permissions enabled by default.
If you need to disable it for the admin user as well there's a module called Jammer.
Answer: use unset($form['actions']['delete']);


python-requests keep session between function

Question: i use requests to login to a website and keep session active
def test():

s = requests.session()

but how can use the variable "s" in another function and keep it alive to perform other post on the current session ? Because the variable is private to the function. I'm tempted to make it global but i read everywhere that it's not a good practice. I'm new to Python and i want to code clean.
Comment: Make the `test` function return the variable `s`. Then pass the variable across the functions. Or group the functions that use the session object and make a class.
Answer: You'll need to either return it from the function or pass it in to the function in the first place.
def do_something_remote():
    s = requests.session()
    blah = s.get('http://www.example.com/')
    return s

def other_function():
    s = do_something_remote()
    something_else_with_same_session = s.get('http://www.example.com/')

A better pattern is for a more 'top-level' function to be responsible for creating the session and then having sub functions use that session.
def master():
    s = requests.session()

    # we're now going to use the session in 3 different function calls
    login_to_site(s)
    page1 = scrape_page(s, 'page1')
    page2 = scrape_page(s, 'page2')

    # once this function ends we either need to pass the session up to the
    # calling function or it will be gone forever

def login_to_site(s):
    s.post('http://www.example.com/login')

def scrape_page(s, name):
    page = s.get('http://www.example.com/secret_page/{}'.format(name))
    return page

EDIT In python a function can actually have multiple return values:
def doing_something():
   s = requests.session()
   # something here.....
   # notice we're returning 2 things
   return some_result, s

def calling_it():
   # there's also a syntax for 'unpacking' the result of calling the function
   some_result, s = doing_something()

Comment: Thank you ! If we pass the function in the first place we can keep it and use it in another ? How to do if the function already return something ?
Comment: I've added a little more detail to the master function so you can see that the session is being used several times in different functions. If you needed it higher up in another function you could return it, or the higher function could create it and pass it down. It's sort of the unit of work pattern. Little bit complex but if you think about your functions as a tree you find the common root function that will call anything else that needs the session. That's where the session should be created.
Comment: Thank you i will use your master function example. Is it correct also to use a class , declare the variable for the class and use it thought the methods of this class ?