How to install pip with Python 3?

Question: I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2.
How can I install pip with Python 3?
Comment: @deamon: you may want to reconsider the accepted answer as `distribute` is deprecated and  [another answer](http://stackoverflow.com/a/17517654/903011) solves the problem.
Comment: related: [easy way to install distribute/pip/virtualenv](http://stackoverflow.com/a/12946537/4279). It supports  Python 3 too.
Comment: Imho this is best than the accepted answer : https://stackoverflow.com/questions/17443354/install-numpy-on-python3-3-install-pip-for-python3/33964956#33964956
Answer: edit: Manual installation and use of setuptools is not the standard process anymore.
If you're running Python 2.7.9+ or Python 3.4+
Congrats, you should already have pip installed. If you do not, read onward.
If you're running a Unix-like System
You can usually install the package for pip through your package manager if your version of Python is older than 2.7.9 or 3.4, or if your system did not include it for whatever reason.
Instructions for some of the more common distros follow.
Installing on Debian (Wheezy and newer) and Ubuntu (Trusty Tahr and newer) for Python 2.x
Run the following command from a terminal:
sudo apt-get install python-pip

Installing on Debian (Wheezy and newer) and Ubuntu (Trusty Tahr and newer) for Python 3.x
Run the following command from a terminal:
sudo apt-get install python3-pip

Note:
On a fresh Debian/Ubuntu install, the package may not be found until you do:
sudo apt-get update

Installing pip on CentOS 7 for Python 2.x
On CentOS 7, you have to install setup tools first, and then use that to install pip, as there is no direct package for it.
sudo yum install python-setuptools
sudo easy_install pip

Installing pip on CentOS 7 for Python 3.x
Assuming you installed Python 3.4 from EPEL, you can install Python 3's setup tools and use it to install pip.
# First command requires you to have enabled EPEL for CentOS7
sudo yum install python34-setuptools
sudo easy_install pip

If your Unix/Linux distro doesn't have it in package repos
Install using the manual way detailed below.
The manual way
If you want to do it the manual way, the now-recommended method is to install using the get-pip.py script from pip's installation instructions.

Install pip
To install pip, securely download get-pip.py
Then run the following (which may require administrator access):
python get-pip.py

If setuptools is not already installed, get-pip.py will install setuptools for you.
Comment: distribute has since been superseded by [setup_tools] (https://pypi.python.org/pypi/setuptools).
Comment: It's worth noting that the distribute install script has a ``--user`` flag that will install distribute just for the current user.
Comment: Pip's website says that it already comes with Python 3.4+ if you downloaded from python.org. However, when I type pip on terminal, I get command not found. So I decided to go through the python3's install docs again, where it mentions that python and pip should be accessed using the commands python3 and pip3 instead. This is not obvious from the documentation on either site.
Comment: For some reason on my instance of Ubuntu 14.04 with python3.4 already installed from apt-get, I also had to run `sudo easy_install3 pip` and then `pip3 install` works from that point on.
Comment: From https://pythonhosted.org/distribute/: "Distribute is a deprecated fork of the Setuptools project.". It is abandoned and not being maintained anymore.
Comment: @TylerCrompton - `easy_install pip`.
Comment: How does one use distribute to install pip? I can't seem to figure it out.
Comment: @ak31 - `pip` is likely a symbolic link to `pip3`. If you do an `ls -l $(which pip)`, it should probably show that.
Comment: This will install pip for `python` not for `python3`, the right way is `sudo apt-get install python3-pip`
Comment: I ran "python3.3 distribute_setup.py". It seemed to work but the only easy_install on my PATH now are "easy_install" in Python2.7, plus "easy_install-2.6  easy_install-3.2  easy_install-2.5  easy_install-2.7" :-\
Comment: I installed pip the manual way , but now I have pip and pip3 both. If I run any of them with `-V` option, I get `pip 8.0.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)`. How do I keep only one and remove the other?
Comment: pip is unfortunately not included with python 3.4 if you're on centos.  See here for details:  http://stackoverflow.com/questions/32618686/how-to-install-pip-in-centos-7
Comment: @tamale - Python 3.4 isn't a default package on CentOS 7 - I've included some additional instructions for people running CentOS 7, assuming they use EPEL to install Python 3.4.
Comment: For those who want to use the manual install (`get-pip.py`), this won't work with python3.0 to 3.2...
Comment: where is windows? I don't say that I'm using only windows, I have no problem to install all of this in ubuntu, by author didn't mention linux, why there such a discrimination, like python, pip doesn't exist for windows...
Comment: @loretoparisi That's what it says in the Answer up there. M Installing it now... :|
Comment: I did have to follow @jamescampbell tip to get it to work fully though.
Comment: ```Collecting pip
  Using cached pip-9.0.1-py2.py3-none-any.whl

Installing collected packages: pip
Successfully installed pip-8.1.1
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.```
This is bit strange...I'm fine with v8, I guess, but it always keeps saying the same message when I try to 'upgrade.' :|
Comment: It is a bit confusing.  I can report that the Debian command worked for Ubuntu 16 and Python3: `sudo apt-get install python3-pip`.  `pip` was NOT installed with `Python 3` for this Ubuntu's PPA.  I used to use Python a lot -- There's really no need for a disregard for forward migration ... Yet it still happens.  Some kind of interface management or poly-fill approach would save lots of trouble.  _Witness_ 17 x answers to the same question and more than a dozen comments on the accepted answer.  Me thinks a _smell_.
Comment: The best way to avoid this kind of problem is using `pyenv`. I tried this solution without using `pyenv` it didn't solve the `TLS` problem.
Comment: Correct me if I am wrong but believe it's the same for Centos and amazon linux
, `sudo yum install python3-pip`
Answer: I was able to install pip for python 3 on Ubuntu just by running sudo apt-get install python3-pip.
Comment: `Unable to locate package python3-pip`. Has it been renamed?
Comment: Then use `pip-3.2 install` (replace 3.2 with your version) to install the packages - also see http://stackoverflow.com/questions/10763440/how-to-install-python3-version-of-package-via-pip
Comment: Are you using Ubuntu 12.04 LTS? It's not available there.
Comment: +1 Confirmed working on ubuntu 13.04 after `sudo apt-get install -y python3.3` and using `type pip3`
Comment: seems to be just pip3 now
Comment: After you install python3-pip, if the package cannot be found, try `python3 -m pip`
Comment: I also just ran this on RPi and used it with `sudo pip-3.2 install [packageName]`
Comment: Thabk you! @yoniLavi and thanks for the link also. Lot of people saying virtualenv/..wrapper but these tools are installed via pip.. So for those who doesn't know (like me) if it's irrelevant the way you install pip we've got here an obvious question. I will use pip3 by now thank you
Comment: pip3 is works, but I had to use sudo pip3 install (for pandas at least)
Answer: Python 3.4+ and Python 2.7.9+
Good news! Python 3.4 (released March 2014) ships with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Nodejs, Haskell, Perl, Go--almost every other contemporary language with a majority open-source community. Thank you Python.
Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this at Does Python have a package/module management system?
Alas for everyone using an earlier Python. Manual instructions follow.
Python ≤ 2.7.8 and Python ≤ 3.3
Follow my detailed instructions at  https://stackoverflow.com/a/12476379/284795 . Essentially
Official instructions
Per https://pip.pypa.io/en/stable/installing.html
Download get-pip.py, being careful to save it as a .py file rather than .txt. Then, run it from the command prompt.
python get-pip.py

You possibly need an administrator command prompt to do this. Follow http://technet.microsoft.com/en-us/library/cc947813(v=ws.10).aspx
For me, this installed Pip at C:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (eg.  C:\Python27\Scripts) to your path (Start / Edit environment variables). Now you should be able to run pip from the command line. Try installing a package:
pip install httpie

There you go (hopefully)!
Comment: I just installed python 3.4.1 from scratch on windows 8. Where is pip? How can i start it?
Comment: After python get-pip.py, I also make a symlink from pip3 in /Library/Frameworks/Python.framework/Versions/3.3/bin (for example) to my system PATH, to make pip3 available on command line.
Comment: By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.
Comment: Ubuntu 14.04, just did `apt-get install python3-dev`, python 3.4 installed, no pip :(
Comment: I can install pip3.4 with Python 3.4 on CentOS 6.5. But I used the same method and failed to install pip3.4 on CentOS 7. Python3.4 is OK though.
Comment: @treesAreEverywhere it'll be in your Python installation. Add the Python bin folder to your path.
Comment: The version I just installed (`Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32`) does not have `pip`  anywhere.
Comment: This is not true: "And, alas for everyone using an earlier Python. There's no plan to ship Pip to you." `pip` is shipped with 2.7.9+ as well as 3.4.0+. Of course that doesn't help people on 2.6 or 3.2, but the majority of people who need to use an earlier Python than 3.4 need to use 2.7.
Answer: if you're using python 3.4+
just type:
python3 -m pip

Comment: On CentOS:6 docker image:

python3 -m pip
/usr/bin/python3: No module named pip
Comment: that did the trick for me, for portalocker: python3 -m pip install portalocker
Comment: Don't forget to use "python3" *anywhere* you see a command solution that uses "python ..." if your alias is set up to use python3 instead of python.  Didn't click for me for a good couple hours
Answer: For Ubuntu 12.04 or older,
sudo apt-get install python3-pip

won't work. Instead, use:
sudo apt-get install python3-setuptools ca-certificates
sudo easy_install3 pip

Answer: Update 2015-01-20:
As per https://pip.pypa.io/en/latest/installing.html the current way is:
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

I think that should work for any version

Original Answer:
wget http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

Comment: I think I've read about easy_install being depreciated due to insecure connections.  I'd read up before using easy_install.
Comment: wget https://bootstrap.pypa.io/get-pip.py && python get-pip.py

This works for me and upgrades pip3
Answer: Single Python in system
To install packages in Python always follow these steps:

If the package is for python 2.x: sudo python -m pip install [package]
If the package is for python 3.x: sudo python3 -m pip install [package]

Note: This is assuming no alias is set for python
Through this method, there will be no confusion regarding which python version is receiving the package.
Multiple Pythons/Virtual Envs
Say you have python3 ↔ python3.6 and python3.7 ↔ python3.7

To install for python3.6: sudo python3 -m pip install [package]
To instal for python3.7: sudo python3.7 -m pip install [package]

This is essentially the same method as shown previously.
Note 1
How to find which python? Do one of the following:
~ » python3 -c "import sys; print(sys.version)"
3.9.5 (default, Nov 18 2021, 16:00:48)

your python3 command spawns:
~ » python3
Python 3.9.5 (default, Nov 18 2021, 16:00:48)
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Notice python 3.9.5 in the second line.
or say you are using virtual env and see where your python points to:
» which python
/home/ganesh/os/np-test/bin/python

Note 2
Change what python3 or python points to:  https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3
Comment: Of all these methods, this is the only way I managed to get pip to install for python3.5 when I have both 3.4 and 3.5 on the system.
Comment: can't thank you enough. managing per version install/uninstall is a nightmare no longer.
Comment: No idea why this answer is upvoted. Question is regarding how to install pip and not how to install packages via pip.

As a side-note, using sudo to install packages via pip is asking for dependency hell. Using pip you probably want to scope to your account or to a virtual environment.
Answer: python3 -m ensurepip

I'm not sure when exactly this was introduced, but it's installed pip3 for me when it didn't already exist.
Comment: Thank you, this command pointed my mistake: I built python 3.5 without libssl-dev package, so PIP was not built
Comment: This also worked on cygwin! First update: `pip2 install --upgrade pip` and `apt-cyg install python3`. Then what you wrote and you've got `pip3`.
Comment: This just works! Just tested on python3.11 ```sudo dnf install -y python311
    update-alternatives --set python /usr/bin/python3.11
    update-alternatives --set python3 /usr/bin/python3.11
    python3 -m ensurepip```
Answer: Older version of Homebrew
If you are on macOS, use homebrew.
brew install python3 # this installs python only
brew postinstall python3 # this command installs pip

Also note that you should check the console if the install finished successfully. Sometimes it doesn't (e.g. an error due to ownership), but people simply overlook the log.

UPDATED - Homebrew version after 1.5
According to the official Homebrew page:

On 1st March 2018 the python formula will be upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7 (although this will be keg-only so neither python nor python2 will be added to the PATH by default without a manual brew link --force). We will maintain python2, python3 and python@3 aliases.

So to install Python 3, run the following command:
brew install python3

Then, the pip is installed automatically, and you can install any package by pip install <package>.
Answer: This is the one-liner I copy-and-paste:
curl https://bootstrap.pypa.io/get-pip.py | python3

Alternate:
curl -L get-pip.io | python3

From Installing with get-pip.py:

To install pip, securely download get-pip.py by following this link:
get-pip.py. Alternatively, use
curl:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Then run the following command in the folder where you have downloaded
get-pip.py:
python get-pip.py

Warning: Be cautious if you are using a Python install that is managed
by your operating system or another package manager. get-pip.py does
not coordinate with those tools, and may leave your system in an
inconsistent state.
Comment: This response shouldn't be so low down.
Answer: If your Linux distro came with Python already installed, you should be able to install PIP using your system's package manager. This is preferable since system-installed versions of Python do not play nicely with the get-pip.py script used on Windows and Mac.
Advanced Package Tool (Python 2.x)
sudo apt-get install python-pip

Advanced Package Tool (Python 3.x)
sudo apt-get install python3-pip

pacman Package Manager (Python 2.x)
sudo pacman -S python2-pip

pacman Package Manager (Python 3.x)
sudo pacman -S python-pip

Yum Package Manager (Python 2.x)
sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel

Yum Package Manager (Python 3.x)
sudo yum install python3 python3-wheel

Dandified Yum (Python 2.x)
sudo dnf upgrade python-setuptools
sudo dnf install python-pip python-wheel

Dandified Yum (Python 3.x)
sudo dnf install python3 python3-wheel

Zypper Package Manager (Python 2.x)
sudo zypper install python-pip python-setuptools python-wheel

Zypper Package Manager (Python 3.x)
sudo zypper install python3-pip python3-setuptools python3-wheel

Answer: Please follow below steps to install python 3 with pip:
Step 1 : Install Python from download here
Step 2 : you'll need to download get-pip.py
Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .
Step 4 : Enter command python get-pip.py in cmd.
Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version
Answer: If you use several different versions of python try using virtualenv http://www.virtualenv.org/en/latest/virtualenv.html#installation
With the advantage of pip for each local environment.
Then install a local environment in the current directory by:
virtualenv -p /usr/local/bin/python3.3 ENV --verbose

Note that you specify the path to a python binary you have installed on your system.
Then there are now an local pythonenvironment in that folder. ./ENV
Now there should be ./ENV/pip-3.3
use
./ENV/pip-3.3 freeze to list the local installed libraries.
use ./ENV/pip-3.3 install packagename to install at the local environment.
use ./ENV/python3.3 pythonfile.py to run your python script.
Answer: Here is my way to solve this problem at ubuntu 12.04:
sudo apt-get install build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev

Then install the python3 from source code:
wget https://www.python.org/ftp/python/3.4.0/Python-3.4.0.tar.xz
tar xvf Python-3.4.0.tar.xz
cd Python-3.4.0
./configure
make
make test
sudo make install

When you finished installing all of them, pip3 will get installed automatically.
Comment: ImportError: No module named 'pip' after I did all these for python3.4.1 from source off the original python website! `Python 3.4.1 (default, Aug  4 2016, 16:56:02)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin`
Answer: This is what I did on OS X Mavericks to get this to work.
Firstly, have brew installed
Install python 3.4
brew install python3

Then I get the latest version of distribute:
wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a

unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo setup.py install
sudo easy_install-3.4 pip
sudo pip3.4 install virtualenv
sudo pip3.4 install virtualenvwrapper

mkvirtualenv py3

python --version
Python 3.4.1

I hope this helps.
Comment: This helped until the `mkvirtualenv py3` line - on OS X El Capitan, i get a `command not found` error.  Also, to actually use python 3 after using brew to install it, i have to run `python3` rather than just `python` which still maps to python 2.7.   are there different steps for El Capitan?
Comment: @hamx0r you would run python3 or you could symlink it:
Answer: If you used the command "python get-pip.py", you should have the 'pip' function for Python3. However, 'pip' for Python2 might still be present. In my case I uninstalled 'pip', which removed it from Python2.
After that I ran "python get-pip.py" again. (Make sure that 'get-pip.py' is saved in the same folder as Python3.) The final step was to add the directory with 'pip' command to $PATH. That solved it for me.
Answer: For python3 try this:
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python

The good thing is that It will also detect what version of python you have (even if it's an environment of python in your custom location).
After this you can proceed normally with (for example)
pip install numpy

source:
https://pypi.python.org/pypi/setuptools/1.1.6#upgrading-from-setuptools-0-6
Answer:
What's New In Python 3.4
...
pip should always be available
...
By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.

https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453
so if you have python 3.4 installed, you can just: sudo pip3 install xxx
Comment: pip3 was not installed when I installed Python 3.4, I had to follow instructions here to get it.
Answer: Assuming you are in a highly restricted computer env (such as myself) without root access or ability to install packages...
I had never setup a fresh/standalone/raw/non-root instance of Python+virtualenv before this post.  I had do quite a bit of Googling to make this work.

Decide if you are using python (python2) or python3 and set your PATH correctly.  (I am strictly a python3 user.)  All commands below can substitute python3 for python if you are python2 user.
wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-x.y.z.tar.gz
tar -xzvf virtualenv-x.y.z.tar.gz
python3 virtualenv-x.y.z/virtualenv.py --python $(which python3) /path/to/new/virtualenv
source /path/to/new/virtualenv/bin/activate

Assumes you are using a Bourne-compatible shell, e.g., bash
Brilliantly, this virtualenv package includes a standalone version of pip and setuptools that are auto-magically installed into each new virtualenv.  This solves the chicken and egg problem.
You may want to create an alias (or update your ~/.bashrc, etc.) for this final command to activate the python virtualenv during each login.  It can be a pain to remember all these paths and commands.

Check your version of python now: which python3 should give: /path/to/new/virtualenv/bin/python3
Check pip is also available in the virtualenv via which pip... should give: /path/to/new/virtualenv/bin/pip

Then... pip, pip, pip!
Final tip to newbie Pythoneers: You don't think you need virtualenv when you start, but you will be happy to have it later.  Helps with "what if" installation / upgrade scenarios for open source / shared packages.
Ref: https://virtualenv.pypa.io/en/latest/installation.html
Answer: To install pip, securely download get-pip.py.
Then run the following:
python get-pip.py

Be cautious if you're using a Python install that's managed by your
  operating system or another package manager. get-pip.py does not
  coordinate with those tools, and may leave your system in an
  inconsistent state.

Refer: PIP Installation
Answer: And for Windows 8.1/10 OS Users just open cmd (command prompt)
write this : C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python36-32\Scripts
then
just write this : pip3 install {name of package}
Hint: the location of folder Python36-32 may get different for new python 3.x versions
Comment: This doesn't answer the question asked, which was about how to install pip, not how to install stuff *with* pip.
Comment: You can also do this in PowerShell of course.

Also the '-32' refers to the 32bit version of Python. So for me the path was .\Python37\scripts\ as I was targeting the 64bit version of Python.
Answer: pip is installed together when you install Python. You can use
sudo pip install (module)
or
python3 -m pip install (module).
Answer: =>Easy way to install Python any version on Ubuntu 18.04 or Ubuntu 20.04 follow these steps:-
Step 1: Update Local Repositories:-
sudo apt update
Step 2: Install Supporting Software:-
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget
Step3: Create directory on your home directory To download the newest release of Python Source Code, navigate to the /python-source-files directory and use the wget command:-
mkdir python-source-files
Step 4: Download the Latest Version of Python Source Code:-
wget https://www.python.org/ftp/python/3.7.5/Python-3.7.5.tgz
"you can change python version by just modifies this:-"3.7.5" with the version you want example:-"3.5.2"
Step 5: Extract Compressed Files:-
tar –xf Python-3.7.5.tgz
or
tar xvzf Python-3.7.5.tgz
Step 6: Test System and Optimize Python:-
cd python-3.7.5 or your version of python.
Step 7: Now configure(Using the ––optimization option speeds code execution by 10-20%.):-
./configure ––enable–optimizations
OR you can also do this also if you facing ssl error:-
./configure --with-openssl
Step 8: Install a Second Instance of Python:-
sudo make altinstall
"It is recommended that you use the altinstall method. Your Ubuntu system may have software packages dependent on Python 2.x.
OR
If you want to Overwrite Default Python Installation/version:-
sudo make install"
Step 9:Now check Python Version:-
python3 ––version
Step 10: To install pip for python3 just go with this command:-
sudo apt-get install python3-pip
Comment: "easy way of installing" and you recommend building the python source? way easier is to use the existing python installation and grab the get-pip.py file.

How to install pip with Python 3?


Why does Musescore not allow saving scores online?

Question: I'm trying to save my scores at the Musescore site. In 2014 it was permitted but now you can't upload or even download scores for free any more.
Does anyone know an alternative ?
Comment: Are you sure? I think I joined MuseScore somewhere around 2016 and I used all the 5 F2P user uploads. I think I also used MuseScore uploading feature like a MIdi converter for my IGCSE exams last year (2017-18).
Comment: How do u upload scores there? I have just 5 scores to upload...
Comment: @user2535338 in the mean time musescore has changed their policy and your can upload as many scores as you want now, even without a pro account
Answer: Last time I uploaded I thought there was a limit to the number of free scores you could store (5 scores from my memory.) You had to get an account after that for more storage. Obviously, they cannot offer unlimited storage for the whole world.
Free offerings like this usually change over time. Typically moving from free and open to commercial. Check the current services description. Don't rely on a free service for critical storage or access.
Comment: By "account...for more storage", I believe you mean a pro account.
Comment: @Dekkadeci, probably. I used a general wording, because services like this change constantly.
Comment: Yeah, that would be a "pro account". "Free" offers up to 10 I think. Might've changed in the meantime, don't know, since I have a "pro account" (which doesn't mean I'm a pro, it's just that they decided on a very badly named account offering).


Significance of a cluster with respect to the whole dataset

Question: I mainly am a machine learning guy and my knowledge of statistics is a bit limited.
I have a (small) dataset of objects described by two categorical variables:
$$
\begin{array}{|l|l|l|l|l|}
\hline
    & \mathsf{'l'} & \mathsf{'u'} & \mathsf{'b'} & \mathsf{Tot} \\ \hline
\mathsf{'2'} & 15  & 9   & 9   & 33  \\ \hline
\mathsf{'3'} & 8   & 5   & 2   & 15  \\ \hline
\mathsf{Tot} & 23  & 14  & 11  & 48  \\ \hline
\end{array}
$$
that obtaining a partition of 6 clusters. One of which is interesting from my point of view:
$$
\begin{array}{|l|l|l|l|l|}
\hline
    & \mathsf{'l'} & \mathsf{'u'} & \mathsf{'b'} & \mathsf{Tot} \\ \hline
\mathsf{'2'} & 8 & 3   & 2   & 13 \\ \hline
\mathsf{'3'} & 3   & 0   & 0   & 3  \\ \hline
\mathsf{Tot} & 11  & 3  & 2  & 16  \\ \hline
\end{array}
$$
From a perspective of frequencies in the whole dataset the probability of obtaining an object of type ('l', '2') is $p_D=P(r=\mathsf{'2'} \wedge c=\mathsf{'l'} )=\frac{15}{48}=0.3125$, whereas for the cluster is $p_C=P(r=\mathsf{'2'} \wedge c=\mathsf{'l'} )=\frac{8}{16}=0.5$
which is an increase of $\frac{p_C}{p_D}=1.6$.
Now, I have been asked about the significance of this "enrichment" given by the clustering with respect to the whole dataset.
I was thinking about a randomization test in which I build the null distribution assigning randomly the cluster labels and calculating the the ratio $\frac{p_{C'}}{p_D}$ (where $C'$ is the randomized clustering) and testing the probability under the null hypothesis of obtaining a ratio of value at least of $1.6$.
Do you think this is a valid procedure? Can you suggest something better?
Answer: To me, this appears to be pretty much random.
At 48 objects, this is not surprising. This is just too little data to yield anything substantial... in particular with this many degrees of freedom.
Testing against a random partitioning will not work. This has been attempted before, but never worked. The null hypothesis is "randomly assigned to clusters"; all you know after rejecting this hypothesis is that your algorithm looked at the data instead of throwing coins.
Don't blindly trust a clustering result. And don't trust an evaluation measure either. Instead: can you explain what the algorithm found? I.e. does the pattern make sense? If not, discard the result. Otherwise, test the pattern on fresh data, and try to use it somehow and check if it is useful.
Comment: I'd suggest to manually study this data (it's *not* very large), instead of betting that some clustering algorithm will perform magic. Clustering usually needs much larger data to work at all, and usually does not handle categorial data well at all...
Comment: I agree with you. Unfortunately, this is a private neuroimaging dataset and cannot be easily extended. This is a preliminary explorative analysis with methods that I am studying. The best I can come up with is a cross-validation of the clustering procedure in order to validate on unseen data the found patterns. What do you think?


How to get a specific entry from a custom ArrayList?

Question: I have an Android app that uses Retrofit to consume an API, puts JSON into a custom ArrayList and then populates a ListView by using a custom ArrayAdapter. This works as intended.
The ListView items display 3 of the 7 values available in the model I used. Now I wanted to make it so that upon clicking a list item, a new activity starts and displays a complete entry, with all the 7 values.
I made the list items clickable with onItemClickListener and made an Intent that starts the new Activity. This Activity has a couple of TextView's that are there to house all the 7 values from a single entry. I made the JSON ArrayList parcelable and passed it as an Extra along with the Intent.
The problem:
I can populate ListView's and RecyclerView's alright, but I don't know how to extract JSON data that's under a specific index. ArrayList.get(x) doesn't work, because the object is custom and doesn't include that method, I think. Here's my ArrayList model:
public class ListModel implements Parcelable {

@SerializedName("id")
private String idno;

@SerializedName("name")
private String name;

@SerializedName("telno")
private String telno;

@SerializedName("street")
private String street;

@SerializedName("city")
private String city;

@SerializedName("hour")
private String hour;

@SerializedName("desc")
private String desc;

public ListModel(String idno,
                 String name,
                 String telno,
                 String street,
                 String city,
                 String hour,
                 String desc) {
    this.setIdno(idno);
    this.setName(name);
    this.setTelno(telno);
    this.setStreet(street);
    this.setCity(city);
    this.setHour(hour);
    this.setDesc(desc);
}

public String getIdno() {return idno;}
public void setIdno(String idno) {this.idno = idno;}

public String getName() {return name;}
public void setName(String name) {this.name = name;}

public String getTelno() {return telno;}
public void setTelno(String telno) {this.telno = telno;}

public String getStreet() {return street;}
public void setStreet(String street) {this.street = street;}

public String getCity() {return city;}
public void setCity(String city) {this.city = city;}

public String getHour() {return hour;}
public void setHour(String hour) {this.hour = hour;}

public String getDesc() {return desc;}
public void setDesc(String desc) {this.desc = desc;}

// Parcel stuff after this

Also, here's a snippet of the JSON:
[{"id":1,"name":"Young","telno":"692-(371)616-8685","street":"96333 Anhalt Court","city":"Loen","hour":"18:38","desc":"Quisque id justo sit amet sapien dignissim vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;"},
 {"id":2,"name":"Fowler","telno":"46-(368)133-6356","street":"5 School Parkway","city":"Onsala","hour":"16:17","desc":"Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius."},

Here's the adapter:
public class UsersAdapter extends ArrayAdapter<ListModel> {

public UsersAdapter(Context context, ArrayList<ListModel> users) {
    super(context, 0, users);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ListModel listModel = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
    }

    TextView hourTV = (TextView) convertView.findViewById(R.id.hourTV);
    TextView idnoTV = (TextView) convertView.findViewById(R.id.idnoTV);
    TextView nameTV = (TextView) convertView.findViewById(R.id.nameTV);

    hourTV.setText(listModel.getHour());
    idnoTV.setText(listModel.getIdno());
    nameTV.setText(listModel.getName());

    return convertView;

}

}
Please let me know if any more code is needed. This is my first app, so please bear with me if I'm missing something obvious, or don't explain myself clearly enough.
Thank you.
SOLUTION EDIT
Here's a working result:
MainActivity.java
public ArrayList<ListModel> dataSource = new ArrayList<>();

// Retrofit fetches and parses JSON here.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {

            Intent detailViewIntent = new Intent(MainActivity.this, DetailView.class);

            ListModel listModel = dataSource.get(position);
            detailViewIntent.putExtra("TAG", listModel);
            Bundle bundle = new Bundle();
            bundle.putParcelable("jsondata", listModel);
            detailViewIntent.putExtras(bundle);
            startActivity(detailViewIntent);
        }
    });
}

DetailView.class
public class DetailView extends AppCompatActivity {

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

    Bundle bundle = getIntent().getExtras();
    ListModel jsondata = bundle.getParcelable("jsondata");

    // Populate 7 TextViews using ListModel getters like so:
    TextView hourTV = (TextView) findViewById(R.id.hourTV);
    hourTV.setText(jsondata.getHour());

Comment: If I understand your problem.. What you are trying to achieve is open a new activity and display the whole response you are getting from retrofit? Right? Why do you need that json? I mean Retrofit maps the response for you, so you can simply share whole object instead of a json. If I am missing something, please post your list adapter too.
Comment: Let me rephrase: I want to expand upon only a specific entry. Say, the user clicks on a list item that has "ID:1, Young, Loen" in it. It starts a new activity with a couple of TextViews that say "ID:1, Young, 692-(371)616-8685, 96333(...)", etc. If I just jammed the whole retrofit response in there, wouldn't that mean all the other people from that JSON get included, too? I'm not sure if Retrofit iterates over that JSON and creates a separate ArrayList object for each person, or just packs everything into one ArrayList? I'm updating the question with my adapter, if it helps.
Comment: Please see the edited answer, I hope it will be more clear after reading this :)
Answer: First of all - ListModel is not an custom ArrayList, it is just parcelable Object, that's why you cannot use ArrayList.get(int).
Now back to the solution.
You have some ListView with an onClickListener, which may look like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // HANDLE CLICK
    }
});

In case you have some collection, lets say List<ListModel>, the position parameter is the one you need. The onClickLister should be:
private List<ListModel> listData;
....
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(...);
        // Get the object that has been clicked
        ListModel listModel = listData.get(position);
        // Pass it to your activity
        i.putExtra("TAG", listModel);
        startActivity(i);
    }
});

If you have any questions or your code is different to this one, please free to ask me.
EDIT

I'm not sure if Retrofit iterates over that JSON and creates a separate ArrayList object for each person

If you have successfully created a ListView from the code you posted, than one ListModel == one person. Thats the magic of Retrofit!
Guess your json hierarchy is like this one:
[
    {"id":1, "name":"somename1",...},
    {"id":2, "name":"somename2",...},
    {"id":3, "name":"somename3",...}
]

Then retrofit takes each JSONObject and converts it into your object (ListModel)

If I just jammed the whole retrofit response in there, wouldn't that mean all the other people from that JSON get included, too?

You wont pass whole retrofit response to that activity by doing
ListModel listModel = listModels.get(position);

As I said, one ListModel == one person. The whole retrofit response is not ListModel, but List (or whatever.. maybe ListModels if you require that from retrofit)
Comment: Thank you for the answer, it was enlightening. My code was similar, but I failed to single out the required ListModel part. I'll try implementing it when I have the chance and then edit the original question to be a bit clearer.
Comment: It works! You've pulled me out of a hole I've dug myself into during the last few days, thank you! I edited the question to include the working result. I guess the title would need to be changed, but I'm not sure how to properly name it.


jQuery to dynamically pass in an element's ID to limit the scope of slideToggle()

Question: In the script below, I'm trying to pass in a reference to the parent container's ID in order to limit the scope of the slideToggle to that element's child elements whose class matches.
How can I alter the code to pass in the ID? The problem is that 'myID .extras' is apparently not the proper syntax.
jQuery(document).ready(function()
{
    jQuery(document).on('click','.toggleExtras', function(e){
        var myEl = jQuery(this).closest('.widget');
        var myID = jQuery(myEl).attr('id');
        jQuery('myID .extras').slideToggle();
        jQuery(this).text(function(el, old){
            return old == "Show Advanced Options" ? "Hide Advanced Options" : "Show Advanced Options";
        });
    });

});

HTML:

Widget Title

        <form action="" method="post">

                    Title:
                    <input class="widefat" id="widget-my_box_cats-4-title" name="widget-my_box_cats[4][title]" type="text" value="">

                <fieldset><legend>Hide Advanced Options</legend>

Answer: Why get the ID, and do a lot of beating around the bush, when you can just find the element directly:
jQuery(document).ready(function() {
    jQuery(document).on('click','.toggleExtras', function(e){

        jQuery(this).closest('.widget').find('.extras').slideToggle();

        jQuery(this).text(function(el, old){
            return old == "Show Advanced Options" ? "Hide Advanced Options" : "Show Advanced Options";
        });
    });
});

Answer: jQuery('myID .extras').slideToggle(); should be jQuery('#myID .extras').slideToggle();
For id selecor you need to use the prefix #. myID is an element selector where it will look for elements with tag-name myID


Getting from $\text{Int}(x)$ to $\text{Ad}(x)$ explicitely

Question: Let $G$ be an algebraic group and $\mathfrak{g}$ its Lie algebra.
If $$\text{Int}(x):G\to G,\text{Int}(x)(y)=xyx^{-1}$$
derives to
$$\text{Ad}(x):\mathfrak{g}\to\mathfrak{g},$$
how do I compute $\text{Ad}(x)(\mathbf{x})$ for $\mathbf{x}\in\mathfrak{g}$?
Comment: What are $G$ and $\mathfrak{g}$? I'm guessing that $G$ is a Lie group, and $\mathfrak{g}$ its Lie algebra!
Comment: Hi Mercy King, apologies for that, this has been added.
Answer: Let ${\rm Inn}_A(B)=ABA^{-1}$. Here "Inn" stands for "inner". Then
the map $${\rm Inn} :G→GL(G) ; A\mapsto {\rm Inn}_A$$
 is an homomorphism sending $A ∈ G$ to an automorphism on $G$.
Differentiating with respect to the second argument, we get a map
$$
Ad=d{\rm Inn}_e :G→GL(g) ;\quad  A\mapsto Ad_A
$$
 This map sends $A ∈ G$ to an automorphism on $\mathfrak{g}={\rm Lie}(G)$:
$$
Ad_A :\mathfrak{g}→ \mathfrak{g} ;\quad  Ad_A(X)=AXA^{−1}.
$$
For further details see other posts at MSE about this question, e.g.,
Adjoint Lie algebra homomorphism


How do you ask "expert level questions"?

Question: I have been asked on several occasions on whether or not the questions I asked were truly "expert level".  How exactly do I determine whether my question is "expert level"?
I ask questions that I don't know the answer to and, since they are above my understanding, I feel that are the closest to an "expert level question".  Is this what we mean by an "expert level question"?
Comment: What if the only experience you have is with pre-grad economic courses?  Should you be excluded from asking questions?
Comment: So being an expert means be acquainted with *every* textbook?
Comment: @Majoko Unless I know everything in every pregrad book or class, I do not see how I can ask questions that are not covered in those mediums. Can you elaborate more on what you mean?
Comment: It really seems like you're trying tu purposefully misinterpret what I'm trying to say. Of course it's impossible to be acquainted with every pregrad subject matter. What I said is just that a good guideline for a question would be that it isn't covered by basic/intermediate texts. If not sure, check beforehand.
Comment: @Majoko I'm trying to understand you, but you aren't making much sense.
To be clear, you want to define an "expert-level" question as a question covering material that is not found in any pre-grad courses? If this is what you mean, then how can people who do not know graduate economics ask questions on this site?
Comment: I think a good start would be to rule out anything that is covered in pregrad economic courses.
Comment: No, I didn't say that. It's not about your degree; it's about being able to ask a question that isn't covered in any pregrad book or class.
Comment: For the last time, you *can* make a question beyond undergrad level even if you don't have a graduate degree. What you know and what you are able to conjecture with this knowledge goes way beyond what your degree dictates.
Answer: The restriction to expert-level questions is specific to the first few days of the site's life, while we're in private beta.
If you don't feel confident that you're asking expert-level questions, simply wait a few days until we're in public beta, and then contribute to the meta discussion about what level of questions we want the site to host.
As Majoko point out, if the answer's in undergraduate textbooks, or on wikipedia, it's probably not expert level. If you can't tell whether it's a question an economics graduate or post-doc might ask, it's probably not expert level.


Interpreting PING Results

Question: I am on Windows and LAN using the command line PING in this format:
ping -a -n 5 -S <source ip> <destination ip>
For the most part, it does what it is supposed to do but I have noticed 3 issues that I am curious to better understand.
Two machines, both offline, respond differently

One says: Reply from <source ip>: Destination host unreachable.
Other says: Request timed out.

Now my understanding is that unreachable means exactly what it says, can't be reached (obviously its off) but the other suggests that it is on, but just not responding (which shouldn't be the case here as it IS off) so why the difference in the way the result is reported?
Additionally, as you can see in the command, the option -a is set which means it is supposed to resolve to machine name, but its not doing that in the results. I suspect it might be a NetBIOS issue but wanted to confirm.
Comment: destination host unteachable does not have to mean that the machine is off it may also be behind a firewall, be configured not to respond to icmp ping packets, etc
Comment: I know that, but in this case I KNOW for a fact they are off, they are on my LAN :)
Answer: Destination host unreachable occurs when the local system or a remote system responsible for routing the packet was unable to determine a route to the destination. If the destination host is in the same subnet but does not respond to ARP, it will also trigger a host unreachable error. So basically this is your computer saying "I don't know where to send this packet, the host is either offline and did not respond to ARP, or I don't know where to route it".
Request Timed Out occurs when there was no echo reply received within the time-out period. This could be due to something like a firewall blocking the request, or network congestion. This usually occurs when a route to the destination is present, but something else is blocking the ping. This is basically your computer saying "I know where to send this packet, I have sent it, but I never received a reply".
Comment: If the destination MAC address is already/still in the ARP cache on your source machine then that would explain why you got **Request Timed Out** instead of **Destination host unreachable**. A **Destination host unreachable** occurs when no ARP response is received but if the destination MAC address is already/still in the ARP cache then there's no ARP broadcast necessary, so a **Request Timed Out** would be the expected result.
Comment: Thank you, that's what I thought too but since both machines are OFF shouldn't they logically have the same response? Unreachable? because .67 and .72 machines are both turned off. Now since my machine has an echo block, then someone pinging ME should get the timed out because my machine won't respond but these two are just off at the time of pinging. Hence my confusion.
Comment: Additionally, from my experience, using `-a` while pinging an ip address (as opposed to pinging a name) will cause ping to issue a rDNS query to the source machines configured DNS server. If no rDNS zone exists or a PTR record for the ip address in question doesn't exist then the ip address can't be resolved to a name. There's no `reverse` lookup functionality for NetBIOS that I'm aware of.
Comment: Ok, that's something to consider. I can clear the caches, and try again and see. Thank you for that. Just to confirm, I think `ipconfig /flushdns` should do the trick, right?
Comment: @GµårÐïåñ That is correct.

Interpreting PING Results


Embedded flash player doesn't load

Question: I wrote a program in C# that, when a user press a button, opens a new form containing an embedded flash object. The flash application needs the user to be logged in, so i added to the source something like
<code>swf.SetVariable("__ses", sid);
</code>
This works fine for 2 user testing the application, while the third one can succesfully open one table, while all the others appear "black", just like if the loader can't get past the loading step.
Has anyone had before a similar issue? or has somebody a suggestion on how to debug this problem? I can't figure out if the problem is in the program, or in some strange flash setting he may have... thank you
Comment: Without more information or code, we won't be able to figure this one out, either.
Answer: For debugging I would suggest putting trace statements in various points of the swf to see where it fails.
http://code.google.com/p/flash-tracer/ is a great tool for viewing flash traces from the browser.
If the flash app needs a login variable to actually work and proceed the variable might not be being passed properly. Passing variables to swfs can be a pain because different browsers have different requirements.
Luckily theres this great library that address's these problems and assures your variables get passed properly each and every time.
http://code.google.com/p/swfobject/
So maybe trace out the session id. If it does not trace that might be why its not getting past the loading step. Then try out swfobject.

Embedded flash player doesn't load


Código Botão VBA

Question: Boas,
criei um ficheiro (base dados consulta) em que a cada número corresponde um PDF (hiperligação).
Tentei criar uma USERFORM para procurar o PDF através do Nº e até aqui está a funcionar.
Gostava de carregar no botão Ver e abrir o PDF mas não estou a conseguir.

Private Sub TextBox1_Change()
Dim intervalo As Range
Dim texto As String
Dim codigo As Integer
Dim pesquisa
Dim mensagem

codigo = TextBox1.Text
Sheets("Folha1").Select
Set intervalo = Range("A2:B10")

pesquisa = Application.WorksheetFunction.VLookup(codigo, intervalo, 2, False)

TextBox2.Text = pesquisa

End Sub

'Código do Botão Ver

Private Sub CommandButton1_Click()
If TextBox2 = "" Then
    MsgBox "Insira o nº da ficha a consultar."
End If

TextBox2.SetFocus

End Sub

Preciso de ajuda para criar o código da tecla ver->ficha
Answer: Para resolver seu problema, basta usar o Hyperlink.Follow na célula desejada:
ActiveSheet.Range("b2").Hyperlinks(1).Follow

Então para encontrar o hyperlink, o método .Find é usado. Refira a esta resposta para mais informações dos métodos de localizar.
Private Sub CommandButton1_Click()
Dim F1 As Worksheet
Dim intervalo As Range
Dim LastRow As Long
'Declara a Planilha pelo nome
Set F1 = ThisWorkbook.Worksheets("Folha1")
'Última Linha
LastRow = F1.Cells(F1.Rows.Count, "A").End(xlUp).Row

Set intervalo = F1.Range("A2:A" & LastRow)
'Caso não encontre TextBox2
If TextBox2 = "" Then
    MsgBox "Insira o nº da ficha a consultar."
'Se os campos de TextBox estiverem preenchidos
ElseIf TextBox2 > "" And TextBox1 > "" Then
'Realiza a procura
    With intervalo
        Set cellFound = .Find(TextBox1, LookIn:=xlValues)
        If Not cellFound Is Nothing Then
            FirstAddress = cellFound.Address
            Do
                'Realiza Ação após encontrar, faz offset de uma coluna para direita e segue o hyperlink. Então após encontrar na Coluna A, segue o hyperlink da coluna B.
                cellFound.Offset(0, 1).Hyperlinks(1).Follow
                Set cellFound = .FindNext(cellFound)
            Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress
        End If
    End With
End If
TextBox2.SetFocus

End Sub

E para evitar o uso de .Select o código de encontrar e preencher o valor em TextBox2, pode ser mudado para:
Private Sub TextBox1_Change()
    Dim intervalo As Range
    Dim texto As String
    Dim codigo As Integer
    Dim pesquisa
    Dim mensagem
    Dim F1 As Worksheet
    Set F1 = ThisWorkbook.Worksheets("Folha1")
    LastRow = F1.Cells(F1.Rows.Count, "A").End(xlUp).Row
    codigo = TextBox1.Text

    Set intervalo = F1.Range("A2:B" & LastRow)

    pesquisa = Application.WorksheetFunction.VLookup(codigo, intervalo, 2, False)

    TextBox2.Text = pesquisa

End Sub

Código Botão VBA


What is the equal control for FederatedPassiveSignInStatus control in .net 4.5?

Question: I have written an STS (security token service) for single sign-on. But i have used .net 4 and the Microsoft.IdentityModel and Microsoft.IdentityModel.Web.Controls.
Now i wanna convert my code to .net 4.5 but there is no namespace for handling the "FederatedPassiveSignInStatus" control. What should do and what is the solution for this issue?
Thanks
Answer: [Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework. The version of WIF addressed by this topic, WIF 3.5, is deprecated and should only be used when developing against the .NET Framework 3.5 SP1 or the .NET Framework 4. For more information about WIF in the .NET Framework 4.5, also known as WIF 4.5, see the Windows Identity Foundation documentation in the .NET Framework 4.5 Development Guide.]
Comment: I know this issue but what is the equal for FederatedPassiveSignInStatus control in .net 4.5?
Comment: In page:http://msdn.microsoft.com/en-us/library/jj157091.aspx. As it said, this method has been discarded:"The classes in Microsoft.IdentityModel.Web.Controls implemented the Federated Passive Sign-In Control, which does not exist in WIF 4.5." But this page may help you :http://social.msdn.microsoft.com/Forums/vstudio/en-US/e10b43a6-c9d3-430b-a02c-8ac8f94136fa/how-to-sign-out-in-wif-45-now-federatedpassivesigninstatus-control-has-gone?forum=Geneva
Comment: System.IdentityModel.Services.WSFederationAuthenticationModule.FederatedSignOut
Comment: Do you know, how can i sign in without using "FederatedPassiveSignIn" control?


PyQT running script twice before pressing button

Question: The button in following script is supposed to open a messagebox after being pressed. But BEFORE the button is pressed, the script already opens TWO message boxes.
I have tried to fix this with the self-argument, but the script opens either two boxes or none.
Any help would be greatly appreciated.
<code>import sys
import subprocess
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow, self).__init__(parent)

        self.win_widget = WinWidget(self)
        widget = QtGui.QWidget()
        layout = QtGui.QVBoxLayout(widget)
        layout.addWidget(self.win_widget)
        self.setCentralWidget(widget)

        self.statusBar().showMessage('Ready')

        self.setGeometry(300, 300, 450, 250)
        self.setWindowTitle('Test')
        self.setWindowIcon (QtGui.QIcon('logo.png'))
        self.show()

        self.win_widget = WinWidget (self)

class WinWidget (QtGui.QWidget) :

    def __init__(self, parent):
        super (WinWidget , self).__init__(parent)
        self.controls()
        self.grid_layout()
        self.showDialog()

    def controls(self):

        self.btn_file = QtGui.QPushButton('Choose Path  ', self)
        self.btn_file.setFont(QtGui.QFont('CourierNew', 12 ,  QtGui.QFont.Bold,False))
        self.btn_file.clicked.connect(self.showDialog)

        self.le_path = QtGui.QLineEdit("Python" ,self)
        self.le_path.setFont(QtGui.QFont('CourierNew' , 11))

    def grid_layout (self) :
        grid = QtGui.QGridLayout()
        grid.setSpacing(2)
        grid.addWidget(self.btn_file , 1 , 0)
        grid.addWidget(self.le_path , 1, 1)
        self.setLayout(grid)

    # THE PART BELOW IS THE ONE THAT OPENS THE TWO BOXES BEFORE BUTTON IS PRESSED ...
    def showDialog (self) :
        self.msg = QtGui.QMessageBox(self)
        self.msg.setText("This is a message box")
        self.msg.setInformativeText("This is additional information")
        self.msg.setWindowTitle("MessageBox demo")
        self.msg.setDetailedText("The details are as follows:")
        self.msg.show()

def main():

    app = QtGui.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>
Comment: You are calling `showDialog` in your constructor
Comment: Many thanks, that works perfectly well. Never would have figured that out by myself ... greatly appreaciated .
Answer: <code>#try with this code. I did some changes.
#If your are not expecting this answer, sorry.

import sys
import subprocess
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow, self).__init__(parent)

        self.win_widget = WinWidget(self)
        widget = QtGui.QWidget()
        layout = QtGui.QVBoxLayout(widget)
        layout.addWidget(self.win_widget)
        self.setCentralWidget(widget)

        self.statusBar().showMessage('Ready')

        self.setGeometry(300, 300, 450, 250)
        self.setWindowTitle('Test')
        self.setWindowIcon (QtGui.QIcon('logo.png'))
        #self.show()

class WinWidget (QtGui.QWidget) :

    def __init__(self, parent):
        super (WinWidget , self).__init__(parent)
        self.controls()
        self.grid_layout()
        self.showDialog()

    def controls(self):

        self.btn_file = QtGui.QPushButton('Choose Path  ', self)
        self.btn_file.setFont(QtGui.QFont('CourierNew', 12 ,  QtGui.QFont.Bold,False))
        self.btn_file.clicked.connect(self.showDialog)

        self.le_path = QtGui.QLineEdit("Python" ,self)
        self.le_path.setFont(QtGui.QFont('CourierNew' , 11))

    def grid_layout (self) :
        grid = QtGui.QGridLayout()
        grid.setSpacing(2)
        grid.addWidget(self.btn_file , 1 , 0)
        grid.addWidget(self.le_path , 1, 1)
        self.setLayout(grid)

    # THE PART BELOW IS THE ONE THAT OPENS THE TWO BOXES BEFORE BUTTON IS PRESSED ...
    def showDialog (self) :
        self.msg = QtGui.QMessageBox(self)
        self.msg.setText("This is a message box")
        self.msg.setInformativeText("This is additional information")
        self.msg.setWindowTitle("MessageBox demo")
        self.msg.setDetailedText("The details are as follows:")
        #self.msg.show()
        self.msg.exec_()

def main():

    app = QtGui.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

#Thanks,
#Subin Gopi
</code>


A question about a simple combinatorial problem

Question: I am reading "Introduction to Combinatorial Mathematics" by C. L. Liu.
And I cannot understand the meaning of "because of symmetry" in the following sentences:
p.7 Example 1-9
"A binary sequence is a sequence of $0$'s and $1$'s. What is the number of $n$-digit binary sequences that contain an even number of $0$'s(zero is considered as an even number) ? The problem is immediately solved if we observe that because of symmetry half of the $2^n$ $n$-digit binary sequences contain an even number of $0$'s, and the other half of the sequences contain an odd number of $0$'s."
Liu says that "because of symmetry".
In fact, if $n$ is an odd integer, the problem is immediately solved by symmetry as follows(but if $n$ is an even integer, the following argment doesn't work):
If a sequence contains an even number of $0$'s, then the sequence contains an odd number of $1$'s.
If a sequence contains an odd number of $0$'s, then the sequence contains an even number of $1$'s.
So, "the number of sequeces which contain an even number of $0$'s" is equal to "the number of sequeces which contain an odd number of $1$'s",
and, "the number of sequeces which contain an odd number of $0$'s" is equal to "the number of sequeces which contain an even number of $1$'s".
Obviouly, "the number of sequeces which contain an even number of $0$'s" $+$ "the number of sequeces which contain an odd number of $0$'s" is equal to $2^n$.
And, by symmetry, "the number of sequeces which contain an even number of $0$'s" is equal to "the number of sequeces which contain an even number of $1$'s".
Finally,
$2^n$
$=$
"the number of sequeces which contain an even number of $0$'s" $+$ "the number of sequeces which contain an odd number of $0$'s"
$ = $
"the number of sequeces which contain an even number of $0$'s" $+$ "the number of sequeces which contain an even number of $1$'s"
$ = $
"the number of sequeces which contain an even number of $0$'s" $\times 2$.
So,
"the number of sequeces which contain an even number of $0$'s" is equal to $2^{n-1}$.
Comment: Now for even sequences consider the sequence one shorter, then add the last digit.
Comment: Liu writes after the above sentences as follows:

"Another way to look at the problem is to consider the $2^{n-1}$ $(n-1)$-digit binary sequences."

Maybe your answer is the second method of Liu.
Answer: Let the number of binary sequences of $n$ digits such that the number of $0$s is even be $E_n$, and similarly define $O_n$ for an odd number of $0$s, with $E_n + O_n = 2^n$. Looking at the sequences of length $n-1$, there are $E_{n-1}$ that have an even number of $0$s, and $O_{n-1}$ that have an odd number.
I then claim that there are four groups of sequences of length $n$:

Sequences where the first digit is $0$, and the remaining sequence of length $n-1$ has an even number of $0$s, such that the whole sequence has an odd number of $0$s (there are $E_{n-1}$ of these).
Sequences where the first digit is $1$, and the remaining sequence has an even number of $0$s, such that the whole sequence has an even number of $0$s (there are $O_{n-1}$ of these).
Sequences where the first digit is $0$, and the remaining sequence has an odd number of $0$s, so the whole sequence has an even number (there are $E_{n-1}$).
Sequences where the first digit is $1$, and the remaining sequence has an odd number of $0$s, so the whole sequence has an odd number (there are $O_{n-1}$).

So the sequences with an even number of $0$s come from groups 2 and 3, while the ones with an odd number come from groups 1 and 4. But the total size of groups 2 and 3 is $E_{n-1} + O_{n-1}$, as is the size of groups 1 and 4, so the two groups are of equal size, and hence $E_n = O_n$.
Answer: The "symmetry" alluded to here is the symmetry between the sets,
\begin{align*}
E &\equiv \{\mathbf{x} \in \{0, 1\}^{\times n} \ | \ \mathrm{number \ of \ 0's \ in \ \mathbf{x} \ even} \} \\
O &\equiv \{\mathbf{x} \in \{0, 1\}^{\times n} \ | \ \mathrm{number \ of \ 0's \ in \ \mathbf{x} \ odd} \} \rm{,}
\end{align*}
the sets of binary sequences with even and odd numbers of $0$'s, respectively. Symmetry means that, to every member $\mathbf{x} \in E$, we can associate exactly one member $\mathbf{y} \in O$. This can be done by, say, flipping the last bit $x_n$ of $\mathbf{x}$, which either increases the number of $0$'s by one (if $x_n = 1$) or decreases the number of $0$'s by one (if $x_n = 0$). In either case, the new sequence, $\mathbf{y}$, has an odd number of $0$'s. It is clear that every such $\mathbf{y}$ can be obtained this way (for any $\mathbf{y} \in O$, we can easily give the corresponding $\mathbf{x}$ by flipping $y_n$ back to $x_n$), and no such $\mathbf{y}$ has more than one corresponding $\mathbf{x}$. Therefore, this association defines a bijection, and so $E$ and $O$ must contain the same number of elements. Since every binary sequence of length $n$ has either an even or odd number of $0$'s, $E$ and $O$ must in fact each contain exactly half of the binary sequences of length $n$.
As a simple example, consider the case for which $n = 2$, where we have
\begin{align*}
E &= \{00, 11\} \\
O &= \{01, 10 \} \rm{.}
\end{align*}
By this mapping, the first element listed in $E$ is associated to the first element listed in $O$, and similarly for the second elements. In the same way, we check that the bijection holds for $n = 3$
\begin{align*}
E &= \{001, 010, 100, 111 \} \\
O &= \{000, 011, 101, 110\} \rm{,}
\end{align*}
and so forth.
Answer: The claim is that one can conclude "by symmetry" that:
Half of the $2^n$ $n$-digit binary sequences contain an even number of $0\text{'s},$ and the other half of the sequences contain an odd number of $0\text{'s}.$
A key thing to notice, which motivates the eventual answer, is that actually the claim is not true for $n=0\!:$ In fact, there's exactly one $0$-digit binary sequence, namely the empty string.  Since the number of sequences of length $0$ is odd, it's obvious that exactly half of them can't have an even number of $0\text{'s},$ since half of an odd number isn't a whole number!
[The empty string (the only binary sequence of length $0)$ has an even number of $0\text{'s}$ in it, so there's $1$ sequence of length $0$ with an even number of $0\text{'s},$ and there are $0$ sequences of length $0$ with an odd number of $0\text{'s}.]$
In any case, the claim not being true for $n=0$ suggests that any symmetry argument can't really be based on the entire string, since one would expect a general string-based symmetry argument to work for $0$-length strings as well as for strings of positive length.
However, we can use a symmetry argument based on a particular bit in the sequence rather than on the entire string (and, as long as $n\gt 0,$ there will be a bit to work with).
So let $S$ be the set of finite sequences of $0\text{'s}$ and $1\text{'s}$ of length at least $1,$ and define a function $f\colon S\to S$ by letting $f(x)$ be the same sequence as $x$ except with the first bit negated (so the first bit in $f(x)$ is $1$ minus the first bit in $x,$ and all the other bits in $f(x)$ are the same as the corresponding bits in $x).$
You can see that, for each $n\ge 1,$ $f$ defines a 1-1 correspondence between the set of $n$-digit binary sequences with an even number of $0\text{'s}$ and the set of $n$-digit binary sequences with an odd number of $0\text{'s}.$


Arithmetic overflow error converting expression to data type datetime. (while displaying date time..)

Question: While executing following error is showing
declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;
select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT

error shows
Arithmetic overflow error converting expression to data type datetime.

Comment: I've normally seen convert expressions like that dealing with *strings* rather than numbers. Do you have to start with a numeric type?
Answer: You issue is that you're trying to convert the numeric to a datetime, and this just isn't working.
You need to turn your numeric into a string first:
declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;

select yr_mnth_dt = cast(cast(@yr_mnth_dt as char(8)) as datetime);

SQL Fiddle with demo.
When you try and convert a numeric type to a datetime, SQL Server tries to add the numeric value as the number of days to the date 01-Jan-1900. In your case this is trying to add millions of days, and hence the overflow error.
CONVERT works fine, too, if you prefer:
select yr_mnth_dt = convert(datetime, convert(char(8), @yr_mnth_dt));

SQL Fiddle with demo.
Answer: I've only seen the conversion used for strings. I can't easily tell whether it's even designed to work with numbers. You could convert the number to a string, then the string to a date. However, I would personally just use DATEFROMPARTS:
SELECT DATEFROMPARTS(@yr_mnth_dt / 10000,
                     (@yr_mnth_dt / 100) % 100,
                     @yr_mnth_dt % 100) AS YR_MNTH_DT

Comment: This is a good approach, but worth noting it's SQL Server 2012 and above only.
Comment: @IanPreston: Hadn't noticed that. *Surely* there's some way of creating a date from its constituent parts prior to that without using a string...
Answer: Why numeric?
Try this
declare @yr_mnth_dt as varchar(10);
set @yr_mnth_dt = '20130822';
select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT

Comment: According the comments from the OP he has to start with a `numeric` type.
Comment: @Ian Preston,
but I see that it is august 22, 2013, not the integer. :-)
Answer: Now we can do simply:
declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;
select cast(str(@yr_mnth_dt) as datetime); // output: 2013-08-22 00:00:00.000


How to make header height relative to (tab) content height?

Question: Hard to explain what i need so i added a image the make things more clear:
Example: See the image Below

I'm building a website with tabbed content on a single page. I want my header and content height to get bigger and smaller when there is more or less content with a total page height that does nog get bigger then 100% When the content is smaller than maximum content size i want the header to become bigger/animate slide down.
How can i make the header and content resize relative to each other and tabbed content size?
Please see the above image for a more clear explanation.
Comment: this may be a starting point: http://jsfiddle.net/vlrprbttst/rR7Uu/4/
Answer: Building on @vlrprbttst's fiddle, this is more or less what you need:
working demo
css
<code>:root, body {
    margin:0;
    padding:0;
    height:100%;
    overflow:hidden;
}
.cont {
    background:black;
}
.wrap { height:100%;}
#header {
    height:75%;
    background:red;
}
#content {
    height:25%;
    padding:0;
    margin:0;
    background:tan;
}
#tabbed.dynamic-height {
    background:violet;
    max-height:80%;
}
</code>
Javascript
<code>$(function() {
    $(window).resize(setHeights);
 setHeights()
});

  function setHeights() {
 $(".wrap").height($(window).height()-$("#tabbed").height());
}
</code>
Comment: Thank you for your reply, its a great step in the right direction. But i need the tabbed content inside #content div. The header background and the content background together fill the whole page. So i need the total content size and header to me relative to each other. Inside the content there will be tabbed content.

Sorry, Your solution was great, my question was'nt clear :-)
Comment: you want the tabbed content inside content and aligned to the bottom of the container?
Comment: Yes, thats what i want, i managed to do that. Problem is the tabbed content must scroll when larger then 60% of window and most heights are relative, the content height does not return the same height as tabbed content (0%). So unless i hardcode the height of content in css, this wont work for me. How do i get the content height to return the same heigth as de tabbed content (a (grand)child div). And if that works, how do i the heights to change when i use another tab with diffrent height?

question is getting more and more complex, sorry about that
Comment: Almost,i need the content height to be the same height as the tabbed content. So content height = tabbed content height + some padding. Header height = 100% - content height


Mesclando duas colunas em uma nova coluna de nome 'Classe' (dataframe Pandas)

Question: df_downsampled[df_downsampled['attack_cat']=="DoS"]

Pega todo o dataframe 'df_downsampled' onde a coluna 'attack_cat' tem o valor DoS.
Dataset: https://www.unsw.adfa.edu.au/unsw-canberra-cyber/cybersecurity/ADFA-NB15-Datasets/
colunas = ['srcip','sport','dstip','dsport','proto','state','dur','sbytes', 'dbytes','sttl','dttl',
             'sloss','dloss','service','Sload','Dload','Spkts','Dpkts','swin','dwin','stcpb','dtcpb',

             'smeansz','dmeansz','trans_depth','res_bdy_len','Sjit','Djit','Stime','Ltime','Sintpkt',

             'Dintpkt','tcprtt','synack','ackdat','is_sm_ips_ports','ct_state_ttl','ct_flw_http_mthd',
             'is_ftp_login','ct_ftp_cmd','ct_srv_src','ct_srv_dst','ct_dst_ltm','ct_src_ltm','ct_src_dport_ltm',
             'ct_dst_sport_ltm','ct_dst_src_ltm','attack_cat','Label' ]

UNSW1 = pd.read_csv('/home/users/p02543/ddos/UNSW-NB15_1.csv',dtype={"srcip":object ,},names = colunas)

UNSW2= pd.read_csv('/home/users/p02543/ddos/UNSW-NB15_2.csv',dtype={"srcip":object ,},names = colunas)

UNSW3= pd.read_csv('/home/users/p02543/ddos/UNSW-NB15_3.csv',dtype={"srcip":object ,},names = colunas)

UNSW4= pd.read_csv('/home/users/p02543/ddos/UNSW-NB15_4.csv',dtype={"srcip":object ,},names = colunas)

UNSW = pd.concat([UNSW1,UNSW2,UNSW3,UNSW4])

  previsores = UNSW.iloc[:,UNSW.columns.isin(('Sload','Dload',
                                                       'Spkts','Dpkts','swin','dwin','smeansz','dmeansz',
    'Sjit','Djit','Sintpkt','Dintpkt','tcprtt','synack','ackdat','ct_srv_src','ct_srv_dst','ct_dst_ltm',
     'ct_src_ltm','ct_src_dport_ltm','ct_dst_sport_ltm','ct_dst_src_ltm')) ].values# atributos previsores

Existem duas colunas que quero "mesclar":
uma chama-se "Label" e tem valor 1 quando é ataque, e 0 em caso contrário.
Na coluna 'attack_cat' me interessa apenas quando seu valor é 'DoS' (e nesta caso, o valor da coluna 'Label' é 1)
Objetivo:
Criar uma nova coluna de nome "Classe" que:
Pegue APENAS os valores da coluna 'Label' quando o valor de attack_cat for 'DoS' (e o valor de' Label' for 1)
(existem outros valores em 'attack_cat' que nao me interessam)
Pegue TODOS os valores da coluna 'Label ' quando for 0 (nao ataque)
Como fazer?
Comment: Olá, está um pouco confuso. Um exemplo de um dataframe que tens e do que pretendes como resultado ajudava.
Comment: @Miguel: Editei a pergunta!
Answer: Da maneira com que a pergunta está formulada entendi que você precisa de uma só coluna que tenha os valores de Label quando attack_cat = "DoS" e os valores de Label quando Label = 0, e para isso a solução seria algo como:
df_downsampled['Classe'] = pd.concat([(df_downsampled.Label[df_downsampled.attack_cat[df_downsampled.Label == 1]]) , (df_downsampled.Label[df_downsampled.Label == 0])], ignore_index=True)

E para evitar os dados que são NaN, chame a coluna como:
df_downsample.Classe.dropna()

Para um novo dataset com o filtro de attack_cat = "DoS" você precisa de:
new_df_downsampled = pd.concat([df_downsampled[df_downsampled['attack_cat']=="DoS"],df_downsampled[df_downsampled.Label==0]])

Comment: os valores de Label quando Label = 1 E attack_cat ='DoS' e os valores de Label quando Label = 0
Comment: Tudo em uma mesma coluna? Com alguma ordenação específica? @EdS
Comment: tudo na mesma coluna. Gostaria de manter na ordem que vem do dataset, pois a nova coluna será usada em algoritmo de Machine Learning!
Comment: Tente o que editei agora.
Comment: Vou testar! Neste código será mantida a ordem do dataset?
Comment: EU recebi o seguinte erro: " ValueError: cannot reindex from a duplicate axis"
Comment: Pode tentar agora? @EdS A ordem será: attack_cat, depois os labels na ordem que estão no dataset.
Comment: nao deu erro mas o resultado está errado: estao aparecendo valores onde Label = 1 mas  attack_cat != 'DoS (estes nao me interessam)
Comment: Eu queria filtrar assim: df_downsampled[df_downsampled['attack_cat']=="DoS"] ou df_downsampled[df_downsampled['Label']==0]]  mas nao sei como fazer o OR acima!
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/84212/discussion-between-vitoriahmc-and-ed-s).


Allow access for anonymous to custom user view mode

Question: I made a custom view mode with display suite for the user entity. It is called "user_teaser" and shows some fields that may be visible for Anonomous user. Unfortunately currently anonymous users cannot see it because of the general "View user profiles" permission which they have no access to.
Which hook should I use to bypass this permission and allow anonymous to see my custom view mode?
I tried hook_entity_view_alter() as below, but this is called already too late I think as it is not even called when the access to the user profile is blocked.
function MODULE_entity_view_alter(&$build, $type) {
  if ($build['#view_mode'] == 'user_teaser') {
    $build['#access'] = TRUE;
    $build['user_image']['#access'] = TRUE;
  }
}

So I would need a hook_entity_access_alter or hook_user_access_alter or a hook_entity_access_query_alter, but they don't exist.
(edit) I found now some lead that might have a solution: How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)
Answer: As you already guessed the permission is checked before building the content, so you will never be able to display any user data without that permission. (At lest not without some programming.)
You could try to grant the View user profiles permission to all user and then use the Field Permissions module and grant access per field. So you can show anonymous users only the fields they should have access to.
UPDATE:
As you have pointed out the above solution introduces some problems with privacy and some additional fields not being hidden on the user profile.
So another suggestion; Remove the Views access check. Views by default bypasses access checks on content (so Views without access checks are considered unsafe). Which might be of benefit to you here. As an alternative you can set a more generic permissions such as View published content to prevent errors from modules like Security Review.

Then under display choose Display Suite and your custom view mode.

You will end up with a View that shows the custom View mode with all selected fields, even for anonymous users. Yet the user profile at example.com/user/1 shows access denied for anonymous users.
Comment: Thanks. I could also do this in Display Suite with the field access there, but, it would be not that perfect as then this will make it hard to get the other view modes of the user correct, as in some view modes the same field should be visible and in other view modes not. Also some of my fields are custom coded display suite fields that are not controlled by the field permissions module.
Comment: To give an example why this would not be a good solution: imagine a view "our team" which shows a publicly visible selection of users and displays them with the view mode "user_teaser" which shows the username and user picture. If I would grant "view user profiles" to all users and limit the visibility of all fields except these two fields, then anyone that goes to user/123 could see the username and image of every user as the view of these fields is not limited by view mode.
Comment: Please see my updated answer.


Practical uses of inclusive start conditions in scanner generator

Question: What are some real-world (not-contrived) lexical-scanning problems where "inclusive scan conditions" (as opposed to "exclusive" ones) are a better solution?
That is, when is %s FOO any better than %x FOO in a (f)lex definition?
I understand the difference in function as well as how to implement the difference in a scanner generator. I'm just trying to get a sense of the kinds of situations where you would legitimately want to mash together different groups of scan rules into a single scan condition.
Full disclosure: Answers will inspire example code for this project.
Answer: "Mashing together" lexical rules is pretty common. Consider backslash-escape handling, which you might want to do more or less the same way in different quoting syntaxes and even regex literals. But those are likely to be combined explicitly.
For an only slightly contrived example of where implicit combination with the INITIAL state might be used, consider lexical analysis of a Python-like language with contextually meaningful leading whitespace. Here, there are two almost-identical lexical contexts: the normal context, in which a newline character is a syntactic marker and leading whitespace needs to be turned into INDENT/DEDENT sequences, and the parenthesised context in which newlines and leading whitespace are both just whitespace, which is not forwarded to the parser. These contexts will only differ in a couple of patterns; the vast majority of rules will be shared. So having an inclusive state which contains only something like:
<IN_PAREN>[[:space:]]+  /* Ignore all whitespace */

might be a simple solution. Of course, that rule would have to be placed before normal whitespace handling so that it overrides while IN_PAREN is active.


Rotate Around Point Towards Mouse

Question: I'm thinking this should be a simple problem but I'm having a lot of trouble implementing this because there are so many things involved.
I am trying to rotate objects defined by their center around a defined point besides the center to face the location of the mouse
I have the defined point in the world space and the mouse's location in the world space as well as the center of each item.
Please avoid giving answers on how to rotate towards mouse or how to rotate around a point individually - I'm trying to do both!
Answer: If this is a fair interpretation of your question, rotating from "last frame" to "this frame",,

If you know the location of the point that you want the sprite to rotate about and you know the distance away from that point that you want the sprite to be, try this:
<code>float radius = ?.?f; // distance from pivot point to sprite
Vector2 spritePivot = new Vector2(?, ?); //location of pivot point
Vector2 mouseToPoint = spritePivot - new Vector2(mouseState.X, mouseState.Y);
mouseToPoint.Normalize();
float spriteAngle = MathHelper.Atan2(mouseToPoint.Y, mouseToPoint.X);
mouseToPoint *= radius;
Vector2 spriteLocation = spritePivot + mouseToPoint;
</code>
later, when drawing the sprite, use spriteAngle & spriteLocation as a params in the proper overload of SpriteBatch.Draw()
Dra
Comment: Does the formula change if the blue square is on the circle and closer to the blue mouse cursor? Also, does the formula change if the center of the blocks are on the circle?
Comment: Why do you use the .Normalize() method? Sorry for so many questions about you've been tremendously helpful with that diagram
Comment: ans1, no, as long as you adjust spritePivot & radius (distance from sprite to pivot) the rest of the algorithm will work.
Comment: ans2, Normalize() is used for 2 reasons. a.) the Atan2() requires a vector of length 1 to properly find the angle. b.) to convert 'mouseToPivot' to a magnitude of 1 so when multiplied by radius, it will be the correct length for adding. - Since both a & b need a vector of unit length (a magnitude of 1), it was handy to normalize the vector at that stage.
Comment: Atan2 is not in the MathHelper namespace, it's in the Math namespace... sry, should be: float spriteRotation = (float)Math.Atan2(...same...);
Comment: There is a bug with this solution. None of the items are being orbitted around the pivot point. Instead, their position (center) is being set to the position - pivotpoint and then they are being rotated around the center. Here is what I wrote...
Comment: float radius = Vector2.Distance(pp, pos
                            Vector2 spritePivot = new Vector2(pp.x, pp.y);
                            Vector2 mouseToPoint = spritePivot - new Vector2(MilitiaGame.Instance.curMousePos.X,
                                MilitiaGame.Instance.curMousePos.Y);
                            mouseToPoint.Normalize();

                            item.Rotation = (float)Math.Atan2(mouseToPoint.Y, mouseToPoint.X);
                            item.Position = spritePivot + mouseToPoint;
Comment: Steve is there any way to reach you besides this incredibly restrictive comment section? I'd like to share with you pictures of my game to show you the problem but I don't want to release these on the public internet.

Rotate Around Point Towards Mouse


How to select certain strings (by index) from a list in a list with linq?

Question: I have an object that looks like this.
List<List<string>> MyData;

The inner List<string> can contain an undefined number of strings but the number is always larger than 0.
In an other object I have the index numbers of the strings I want to select.
The Index number is located in MyObject.Number;
How can I get a List<List<string>> object with only the strings present at the given indexes?
I tried the following:
List<List<string>> test = new List<List<string>>();
List<MyObject>.ForEach(p => test.Add(MyData.Select(q => q[p.Number]).ToList()));

This didn't worked out well since I got a list with the string seperate in lists.
Example:
I got a List with 100 List<string> in it. The List<string> contains 5 strings.
List<MyObject> tells me he has the indexes 0 and 2.
The code I tried returned to me a list with two lists in it. The first list contained all the strings in 0 location of List<string>, the second list all the strings in the 2 location of List<string>.
I wanted a list with 100 lists and in every list 2 strings.
Please help me to solve this problem.
Feel free to ask more information if needed.
SOLUTION:
List<List<string>> MyResult = MyData.Select(l => MyObjects.Select(p => p.Number).ToList().Select(i => l[i]).ToList()).ToList();

Answer: I think this is what you want (indexes is the collection of requested indexes)
var indexes = new List<int>() {0, 2};
var whatYouWant = strings.Select(item => indexes.Select(index => item[index]).ToList())

Comment: This answer is wrong. It selects just char 0 and 2 of each string in the list, but not the string 0 and 2 of the list by index.
Comment: @monotomy I don't think it's wrong, don't forget that strings contains a list of list of strings, not a list of strings
Answer: In linq you can pass two parameters, the second one will be integer with index number of current element.
List<string> strings = new List<string>();
strings.Where((s, i) => i == indexToLookFor).Select(s => s);

This way you can easily return only items with indexes you are looking for. In your case you can use something like this:
strings.Where((s, i) => indexes.Contains(i)).Select(s => s);

Of course this is just an example, but I'm sure you can adjust it to fit to your case.
Comment: @Pako Thank you for this. It was helpful.
Answer:         var lists = new List<List<string>>
        {
            new List<string> { "1", "2", "3", "4" },
            new List<string> { "5", "6", "7", "8" },
            new List<string> { "9", "10", "11", "12" },
        };

        var indexes = new List<int> { 0, 2 };

        var result = lists.Select(l => indexes.Select(i => l[i]).ToList()).ToList();

        foreach (var list in result)
        {
            Console.Write("list:");

            foreach (var elt in list)
            {
                Console.Write(elt + ",");
            }

            Console.Write(" / ");
        }

Output:
list:1,3, / list:5,7, / list:9,11, /
Answer: var indexes = myObjects.Select(obj => obj.Number);
var result = test.Select(list => indexes.Select(idx => list[idx]).ToList()).ToList();

myObjects is list of MyObject instance.


Need to precisely set Highcharts axis min/max after chart creation

Question: Most of the time, our app wants to let Highcharts decide the y axis tick positions for a chart. But the user can select a "Customize Range" command and specify custom min and max for the y axis after the chart has been created and shown. Purpose: user may want to export charts that line up with other charts they've made. I have tried a number of things including the following code, but Highcharts continues to follow its own preferences for the min, max and tickInterval (e.g. it does not respect {5,25} or {-5,35}. And my custom tickPositioner callback is not being called.
okClicked() {
    this.axis1.startOnTick = false;
    this.axis1.endOnTick = false;
    this.axis1.alignTicks = false;
    this.axis1.tickPositioner = this.getCustomTicks.bind(this, this.axis1, this.yMin1, this.yMax1);
    this.axis1.setExtremes(this.yMin1, this.yMax1);
    this.axis1.chart.redraw();
}

Comment: Are you looking for something like this? http://jsfiddle.net/vrwxunqa/
If yes, let me know so I create a full answer and describe it more precisely.
Comment: @raf18seb : putting {5,25} in your fiddle demonstrates my problem. thx
Comment: Just use "tickInterval: 5" or calculate any other value.
Comment: @raf18seb try tickInterval=5, min= -5, max=35 in fiddle. Same issue.
Comment: Everything looks fine in jsFiddle in my answer. If you're still using link from my comment, increase height of the chart in HTML.
Comment: It appears that several answers were correct, that I need to call update() on the axis (passing in min, max, and tickInterval in an options object). It seems I won't need to use a custom tick proc for my situation.
Comment: Using update() is the best approach, it gives us a lot of flexibility. If you have any other specific question, I will be happy to help you, just specify your question precisely. If you've got your answer already, please mark it as accepted. Best regards!
Answer: You can fire chart.update function after the button is clicked, and set axes options to whatever you want them to be:
$('.btn').click(function() {
    Highcharts.each(Highcharts.charts, function(chart, i) {
        chart.yAxis[0].update({
            max: 25,
            min: 5,
            startOnTick: false,
            tickInterval: 5
        });
    });
});

http://jsfiddle.net/BlackLabel/obfudy23/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update
Answer: It is possible to solve this issue by adding a simple input field to your html like this:
Min: <input id="min">

Max: <input id="max">
<button id="update">Update y-axis </button>

Then we need a function which activates on click of the button. Inside this function we will update the Highcharts chart.
$('#update').click(function () {
    chart.update({
       yAxis: {
           min: document.getElementById("min").value,
           max: document.getElementById("max").value,
           tickInterval: 5 //do calculations here to get needed tickInterval
       }
    })
});

As shown in this JSFiddle, it alters the y-axis. You can extend the update function however you like, just override the previous settings like happened in the code shown above.
On a sidenote: It has to be noted that in the fiddle the y-axis can be off at times, depending on the inserted values. The tickInterval should be dynamically calculated for this to work.
Comment: If you plug in {-5, 25} in the fiddle, you'll see my issue. I need to override Highcharts' smart tick generation.
Comment: @JoeNolan See my updated answer: you can just override tickInterval within this update as well to solve the problem. I set it on 5 for the demo purpose.


Request header value added in the Middleware is not reaching hub via Azure SignalR Service

Question:
Request headers are passed on from the front end to the app service the middleware configured adds some additional headers to the request, but when this reaches the hub via (Azure Signal service) only the front end headers are available. The headers that was added in the middleware are lost? My StartUp.cs looks like below
<code>  services.AddSignalR(
                hubOptions =>
                {
                    hubOptions.EnableDetailedErrors = true;
                })
            .AddAzureSignalR(config =>
            {
                config.Endpoints = new[]
                {
                    new ServiceEndpoint(new Uri(Configuration.GetValue<string>("SignalRServiceUrl")),
                        new ManagedIdentityCredential(Configuration.GetValue<string>("AZURE_CLIENT_ID")))
                };
            });
</code>
and below is for middleware and hub
<code>app.UseMiddleware<AddHeaderMiddleware>();

  app.UseAzureSignalR(endpoints =>
            {
                endpoints.MapHub<TestHub>("/api/TestHub");
            });
</code>
Answer: Yes, all the header which you have set inside the web application middleware will missed. Only firstly negotiate will go to the server, then All the connection is make as the web-socket and client connect to the Azure Signlar Service not your application's hub.
If you enabled the Azure SignalR Server for your SignalR application. All the response which send from your SignalR application hub will firstly send to the Azure SignalR service and Azure SignalR service will return the response back to the client by using the web-socket.


How to make image slider automatically in html with swiper class?

Question: I have swiper-container swiper-slider class for image slide. Here the problem is, Images are not sliding automatically. I have to make image slider work automatically without clicking the next and prev button.
Here is my full code. It might be help to answer. Instead of carousel her used Swiper class please help.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="keywords" content="intense web design multipurpose template">
    <meta name="date" content="Dec 26">
    <link rel="icon" href="images/favicon.ico" type="image/x-icon">

  <link rel="stylesheet" type="text/css" href="css/theme.css">

  <link rel="stylesheet" type="text/css" href="css/admin-forms.css">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Montserrat:400,700%7CLato:400,700'">
    <link rel="stylesheet" href="css/style.css">

                   |
                   |
                   Rnt |
                     |
                  Cot

            <button title="Close (Esc)" class="pswp__button pswp__button--close"></button>
            <button title="Share" class="pswp__button pswp__button--share"></button>
            <button title="Toggle fullscreen" class="pswp__button pswp__button--fs"></button>
            <button title="Zoom in/out" class="pswp__button pswp__button--zoom"></button>

          <button title="Previous (arrow left)" class="pswp__button pswp__button--arrow--left"></button>
          <button title="Next (arrow right)" class="pswp__button pswp__button--arrow--right"></button>

Comment: Have a look at this example [carousel](https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_rr)
Comment: Yes i had look into that. But i have declared swiper class in whole page. Now i can't turn into carousel.
Comment: Are you using autoplay property? and have you added proper .js files into your code at right places? double check it.
Comment: Yes. Correctly added .
Comment: You will need to provide a more complete snippet/link with the JavaScript included for the slider, so that a working example can be tested and seen to fail. It can't be diagnosed if we have to work on the assumption that everything is definitely correctly added.
Comment: You're using the markup for Swiper but the init code for Slick? Also, why are you targeting .swiper-slide, rather than the container (as in the Slick documentation)?
Comment: I am newbie for this. I didn't get about swiper and container.? pls help
Comment: Your HTML is written for a slider called Swiper. Your JavaScript is writter for a slider called Slick. The slider script you have loaded is also for Slick. You can't use the two together - your slider HTML is wrong, it needs to follow the Slick documentation.
Comment: Now what i have to code here.?
Comment: You either need to use the guide here http://kenwheeler.github.io/slick/ or replace the Slick scripts with Swiper. Given you much markup you have in there, it might be easier to go with Swiper.
Comment: There is no auto slider explanation.
Answer: You need to initialize Swiper with the autoplay setting enabled in your JavaScript:
var mySwiper = new Swiper('.swiper-container', {
  autoplay: {
    delay: 5000,
  },
});

Source: Swiper Parameters - Autoplay
Edit: The updated code shows that the Slick slider script is being used, but the markup is for Swiper. The HTML needs to be written according the Slick documentation, and the correct element then needs to be targeted to initialize it.
Comment: I added this code in JS but not automatically sliding yet.
Answer: If I've guessed it correctly, You might want to use the carousel instead of swiper class. Less fuzz and more fun.
Bootstrap Carousel
Hope it helps.
-N Baua