How to map Windows ACL to Linux ones on a CIFS share?

Question: Context
We have a Windows server with an Active Directory domain and a network share.
I have a Linux machine and I want to mount the share.
sudo mount -t cifs //server/share /mnt/share -o user=[act-dir user],domain=[domain],uid=[linux user],gid=[linux group]

It's more or less OK. My Linux user gets mapped to all files on the share and some of the ACL are translated. But I want to go a level further:

More than one user is connected to the Linux box
Each Linux user has a dedicated Active Directory account
I want each Windows owner to be mapped to the corresponding Linux owner if it exists

A solution and the problem
Samba offers the mount option cifsacl which requires to set-up cifs.idmap and winbindd. Both are installed, I've read both man pages and tried to configure them but it does not work. The newly mount command is now:
sudo mount -t cifs //server/share /mnt/share -o user=[act-dir user],domain=[domain],cifsacl

But everything is mapped to root:root, which means the cifs.idmap could not be performed.
Actually, I'm not all surprised because I did not understand where to write the actual mapping so where should I write that Windows userX actually maps to Linux userY? And I'm not sure that the winbindd configuration is correct, what should be the minimum set of parameters and is smbd and/or nmbd require to run? Do I need to open the port in the firewall?
Background infos
Share structure
The shared directory has several sub directories, some commons and some "privates" (although the private ones are actually readable by everyone). Each user would need to access from time to time the common space, and also other user private directories, but mainly/often their own directory.
Tech data

RHEL 6, Samba 3.5.6
Ubuntu 12.04, Samba 3.6.3
Comment: Can't you have each user map to the Windows share individually, with their own credentials, and let the Windows server manage the access rights?  That's how SMB is meant to work, I'm not sure whether what you are trying to do is possible.  (Note that there's no technical reason why Samba couldn't do it, I just don't see why they'd bother.)
Comment: The permissions should already apply, albeit based on the user account specified in the mount command rather than on the user accessing the mount point.  Anyway, we're getting sidetracked, since this isn't what you're trying to do.  Doesn't look like anyone here knows the answer, have you tried the Samba mailing lists?
Comment: What do you mean by "each user map to Windows share individually"? Do you mean that each user mount the share in their local space? I'm adding some extra infos about the share context in the question to clarify our current status.
Comment: yes, looking from a Windows perspective, I would expect each user to establish their own connection to the file server, using their own Windows username and password to do so.
Comment: OK, understood. But think of this share from a Windows client perspective. I can access it from my Windows client and some permissions rules apply, I cannot access or modify every files or directories. I just would like these permissions to be mirrored/mimicked (as far as possible) to the Linux CIFS mount point.
Comment: @HarryJohnston good point. I'm going to ask there.
Answer: How to set up a CIFS Multiuser Mount
CIFS is a session-based protocol. This means that the session runs with the privileges of the user who logged on for the CIFS session. Therefore, the normal way of using CIFS is to mount the shares at user login time with the privileges of the user logging in. This is what the protocol was designed for.
Nontheless, the Linux CIFS driver offers a way to mount the share at startup time already. This is called a multiuser mount. The strategy for a multiuser mount is to mount the share at startup time with minimal privileges. For every user accessing the share, the CIFS driver will internally create a separate CIFS session with the server.
When a user accesses the multiuser-mounted share for the first time, the CIFS driver needs to create a CIFS session with the fileserver for this user. This requires security information, e.g. a username and a password. Because the driver cannot prompt for login data, it will look into the kernel keyring for the current Linux user. If a suitable security information can be found, then the CIFS driver will use it to create a CIFS session for the current user with the fileserver and the user can access the share.
This post may look like a howto, but in fact it is meant as a collection of possible pitfalls.
Step 1: Create a share SHARE at the fileserver FILESERVER and a local user CIFS_GUEST on the fileserver with minimal privileges. The user must only be allowed to mount the share from a remote machine. The password of the user must never expire.
Notes & Pitfalls:

The user does not need to be in the local "Remote Desktop Users" group of FILESERVER.
If the share SHARE is a so-called "administrative share", then the users (including CIFS_GUEST) would have to have administrative privileges. It is recommended to create a share of the normal, non-administrative type.
Step 2: Mount the share from your Linux machine, e.g.
mount.cifs //FILESERVER/SHARE /mnt --verbose -o domain=FILESERVER,username=CIFS_GUEST

This should mount the share properly. If not, I recommend a look at the manpage mount.cifs(8).
Notes & Pitfalls:

Make sure to specify the option domain=FILESERVER. Otherwise, the fileserver may assume that CIFS_GUEST is a domain (non-local) user and deny access.
If you run into trouble with authentication, check the logs of the server(e.g. Windows event logs in case of a Windows fileserver)
You may want to add the mount option noperm to disable permission checking on the client side. The permissions are enforced by the server anyway.

Step 3: Mount again with the multiuser option:
umount /mnt
mount.cifs //FILESERVER/SHARE /mnt -v -o multiuser,domain=FILESERVER,username=CIFS_GUEST

Verify that multiuser has been used:
mount | grep cifs

Step 4: Create a credentials file for automatic, non-interactive mounting. Protect it against all non-root access.
File contents of /etc/cifs.SHARE.cred:
username=CIFS_GUEST
password=<pass>
Domain=FILESERVER

Then execute:
chown root /etc/cifs.SHARE.cred
chmod 600 /etc/cifs.SHARE.cred

Notes & Pitfalls:

Make sure that the credentials file does not contain a byte order mark (BOM) when using UTF-8 encoding. Otherwise you may get a spurious "Credential formatted incorrectly" message from mount.cifs.

Step 5: Try to Mount the share with the credentials file. This should be completely non-interactive now:
umount /mnt
mount.cifs //FILESERVER/SHARE /mnt -v -o multiuser,credentials=/etc/cifs.SHARE.cred

If this works, you can add the mount to /etc/fstab:
...
//FILESERVER/SHARE /mnt cifs rw,auto,multiuser,credentials=/etc/cifs.SHARE.cred 0 0
...

Notes & Pitfalls:

The option auto has been added for automatic mounting of the share.

Step 6: Login as normal user at the Linux machine now. Try to access the mounted share, e.g.
cd /mnt
ls

The permission should be denied.
Then, manually store CIFS credentials in the session keyring:
cifscreds add FILESERVER -u <username>

You will be prompted for a password. Afterwards, you should be able to access the share, if <username> has access permission for the share on the fileserver.
Notes & Pitfalls:

You can use your Windows Explorer to verify that <username> has Access permissions for the share. This way, you can rule out that the error is on FILESERVER.
If cifscredsgives a warning about a non-persistent session keyring, then type keyctl session and try again.
You can display the contents of the keyring with keyctl show -3.
The cifscreds will not create the CIFS session with the fileserver. It merely puts security info into the keyring, so that the CIFS driver can use it to create a CIFS session when you access the share. This means that changing the key in the keyring with cifscreds update ... will leave you logged on with the old user (!).

Step 7: Finally, the step of feeding the keyring can be automatized. As root, add the following lines to your PAM configuration (e.g. /etc/pam.d/login):
...
auth optional pam_cifscreds.so debug
...
session optional pam_cifscreds.so domain=<AD Domain> debug
...

The first line captures the password on login. The password is stored until the session is created. When the session is created, then the second line will put the record into the keyring. There will be no need to call cifscreds and the share should be accessible immediately after login.
Notes & Pitfalls:

You may want to remove the debug option after testing to reduce logging verbosity.
Make sure that both lines are executed in every case in the PAM stack. (sequence of entries in the configuration file)
You can replace the optional with required to enforce authentication with the fileserver.
Before the second line, the existence of a permanent session keyring should be ensured. If in doubt, add the following line immediately before the second line: session required pam_keyinit.so
Both lines should leave a messages in the system logs when using the debug option.
The same modifications should also be made to the configuration of other PAM-Aware login programs, e.g. to /etc/pam.d/sshd, /etc/pam.d/xdm, ...

Up to this point, the access permissions to files and folders on the share are enforced by the FILESERVER. The permissions, user names and group names displayed on the Linux side are completely wrong. In order to get them properly, add the mount option cifsacl and set identity mapping. However, this probably requires, among other things, setting up the Winbind Service. Additional information can be found in the manpage mount.cifs(8).
Answer: You would probably need to use the username map functionality inside samba (winbind) for the mapping to work so that winbind knows about the AD account for every Linux user. I believe username map can take commands and lists (and some pattern conversions), but it's far easier if the Linux usernames can match the AD usernames, by using pam_winbind for instance. I guess that when the mapping is working you can actually start verifying whether the share is working as well.
Comment: I've look for a winbind tutorial, but I'm stuck at the "Enter the following command to make the Samba server join the domain, where PDC is the name of your PDC and Administrator is a domain user who has administrative privileges in the domain." I don't have and can't have such privileges. So am I screwed? Is it mandatory that my machine join the domain?
Comment: Yes it is, for the funtionality you want you need to delegate credentials, which won't be possible without being in the domain afaik.
Comment: That's a pity... Well I hope someone has another possible answer, or I will have to talk with our IT dept.
Comment: computer account can also be pre-created by the admins AFAIK


How to put two concat queries into the same table as two columns

Question: I've just started using MySQL and I can't find the answer to this anywhere maybe because it doesn't exist?
I want to put these two together in one table as two columns
SELECT CONCAT(Name, ' ',Category) as Pet_Name_and_Category
FROM Animal

SELECT CONCAT(firstname, ' ',lastname) as Customer_Name
From PetCustomer

So the table I want would look something like:
Gary, Snail               Spongebob Squarepants

Sandy, Squirrel           Patrick Star

Where those are two separate columns in the same table.
Comment: How these two tables are related to each others?
Comment: Don't do this ! You're confusing data storage with data retrieval and display. -( I'm s little disappointed that others have failed to point this out )
Comment: `INNER JOIN` or `UNION`?
Comment: The two tables are not related to each other.  They are two separate tables.
Comment: I don't think I want either union or inner join.  I want only 2 columns created by 2 strings each from 2 different tables.
Comment: @user2045948 If the tables are not related, then you cannot have a proper join. Therefore, you cannot know the owner of each pet 'coz there is no relation between these two tables. If you want two columns, matching each pet to the owner, then you have to use a join and not an union.
Answer: Try this,
select Name || ' ' || Category from Animal
union
select firstname || ' ' || lastname from PetCustomer;

If you want these as a separate column, then you can use this,
select Name || ' ' || Category as pet, firstname || ' ' || lastname as owner
from Animal, PetCustomer
where <join_condition_depending_on_table_structure>;

Answer: You need to use an INNER JOIN, so something like:
SELECT
    CONCAT(Name, ' ',Category) as Pet_Name_and_Category,
    CONCAT(firstname, ' ',lastname) as Customer_Name
FROM Animal
    INNER JOIN PetCustomer ON Animal.Customer_id = PetCustomer.id

The join syntax depends on how the 2 tables relate. With other words

How do you know that 'Spongebob Squarepants' owns 'Gary, Snail'?

If they are not related and you just want to show them next to eachother, use 2 separate queries. (example in PHP)
$animals = $db->query("SELECT CONCAT(Name, ' ',Category) as Pet_Name_and_Category FROM Animal");
$customers = $db->query("SELECT CONCAT(firstname, ' ',lastname) as Customer_Name From PetCustomer");

while (list($animal) = $animals->fetch_row() || list($customer) = $customers->fetch_row()) {
    echo $animal, "\t", $customer, "\n";
}

Comment: Thought of this, but the OP mentions that the tables are not related. Therefore, the said join cannot be used.
Comment: @Orangecrush missed that, thanks for pointing it out. I've added an example for this to my answer.
Answer: Maybe try subquery:
SELECT
    (SELECT CONCAT(Name, ' ',Category)
     FROM Animal
     WHERE <column> = <search_argument>)  as Pet_Name_and_Category ,
    (SELECT CONCAT(firstname, ' ',lastname)
     FROM PetCustomer
     WHERE <column> = <search_argument>) AS Customer_Name
FROM <first table>

Comment: This only works if the subqueries both return one row and can therefor not give the specified result.
Comment: Yes, subqueries can return only one result per row from main table. So there are WHERE condition in which you reference to actually row, that's why I put .
Comment: You can see that the example result has 2 rows, which is impossible with this query.
Answer: If you need to use CONCAT twice for the same table, regardless of the condition, you can use this:
SELECT
    CONCAT(TitleOfCourtesy, ' ', FirstName, ' ', LastName) AS NameEmployee,
    CONCAT(PostalCode, ' ', Country, ' ', Region, ' ', City, ' ', [Address]) AS FullAddress
FROM Employees
WHERE 1=1


interpolation of transformPerspective openCV

Question: I have made a small program that reads an image, transforms the perspective and then redraws the image. Currently I rewrite each pixel to the output manually but this way a lot of points are lost and the result is image that is very faint (the larger the transformation the fainter the image). This is my code:
U, V = np.meshgrid(range(img_array.shape[1]), range(img_array.shape[0]))
UV = np.vstack((U.flatten(),V.flatten())).T
UV_warped = cv2.perspectiveTransform(np.array([UV]).astype(np.float32), H)

UV_warped = UV_warped[0]
UV_warped = UV_warped.astype(np.int)

x_translation = min(UV_warped[:,0])
y_translation = min(UV_warped[:,1])

new_width = np.amax(UV_warped[:,0])-np.amin(UV_warped[:,0])
new_height = np.amax(UV_warped[:,1])-np.amin(UV_warped[:,1])

UV_warped[:,0] = UV_warped[:,0] - int(x_translation)
UV_warped[:,1] = UV_warped[:,1] - int(y_translation)

# create box for image
new_img = np.ones((new_height+1, new_width+1))*255 # 0 = black 255 - white background

for uv_pix, UV_warped_pix in zip(UV, UV_warped):
    x_orig = uv_pix[0] # x in origineel
    y_orig = uv_pix[1] # y in origineel
    color = img_array[y_orig, x_orig]

    x_new = UV_warped_pix[0] # new x
    y_new = UV_warped_pix[1] # new y

    new_img[y_new, x_new] = np.array(color)

img = Image.fromarray(np.uint8(new_img))
img.save("test.jpg")

Is there a way to do this differently (with interpolation maybe?) so I won't loose so many pixels and the image is not so faint?
Answer: You are looking for the function warpPerspective (As already mentioned in answer to your previous question OpenCV perspective transform in python).
You can use this function like this (although I'm not familiar with python) :
cv2.warpPerspective(src_img, H_from_src_to_dst, dst_size, dst_img)

EDIT: You can refer to this OpenCV tutorial. It uses affine transformations, but there exists similar OpenCV functions for perspective transformations.
Comment: Thanks for your fast response.
Comment: However, my output will be in coordinates. Someone else told me that the problem with warpPerspective is that it doesn't work with large translations apparently very well.
Comment: Yes it does work, only if the translation is too large, your source image  will leave the field of view of the destination image, so you do not see anything. What do you mean by "my output will be in coordinates" ?
Comment: The image is taken from the real world, They will therefor be real world coordinates
Comment: So your image does not contain colors but coordinates in meters ?
Comment: It does contain colors (or grayscale). Maybe this explains what I want:
I have taken an multiple images under an angle of a beach (images need to be stitched in the future). I want to rectify the image by placing the points in the image in the correct X/Y-coordinate in the real world (and rectify it such that in the final image I'm no longer "looking at an agle" but from above (as if it where taken from a helicopter))
Comment: If the image you want to transform contains colors, then you may use `warpPerspective`, which will take care of the interpolation issues. Now, the actual transformation you want to apply to the image is described by matrix `H`, so you should estimate this matrix consistantly with the rectification you want to achieve. And this is the role of function `cv2.getPerspectiveTransform`.
Comment: You seem to be confused about the image stitching processing chain... See the edit in my answer.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48078/discussion-between-yorian-and-aldurdisciple)


Two smooth bounded connected domains in $\Bbb R^d$ with the same boundary are identical

Question: Let $\Omega_1,\Omega_2\subset\Bbb R^d$ be two connected opens such that $\overline{\Omega_1}$ and $\overline{\Omega_2}$ are smooth bounded connected manifolds with boundary. Then I suspect that if $\partial\Omega_1=\partial\Omega_2$, then $\Omega_1=\Omega_2$, however, I don't see how to prove this. Is the correct to solution to put some normal vector field on the boundaries and use that?
Comment: In the question I required the manifolds to have codimension $0$.
Comment: The fact that each manifold contains an open of $\Bbb R^d$ implies that they must be if codimension $0$.
Comment: The important point here is the difference between a sphere and Euclidean space. Yes, in the sphere there are two distinct domains with the same boundary, but Euclidean space is not a sphere.
Comment: What about the upper and lower hemispheres of a sphere? Specifically you can write $S^2 = D^2\cup S^1 \cup D^2$, where one copy of $D^2$ is a disk "stretched" to a sheet covering the upper hemisphere, another is a similar disk but in the lower hemisphere.

Here the $=$ is "homeomorphic", but if you decompose $S^2$ in such a way you should have the lower/upper parts having the same boundary, but being distinct.
Comment: Did you remember to post that?  I don't currently see that requirement.

Additonally, the "stretched copies of $D^2$" should have interior of dimension $2$, so if I'm understanding the concept of codimension right they should have codimension $0$, right?
Comment: This looks like something that follows from the triviality of singular homology  in $\mathbb{R}^d$.
Comment: I also get that sense -- however, I don't immediately see precisely how we can apply it. Maybe we should start by considering the components of $\partial\Omega$?
Answer: Each $\Omega_i$ defines an element $c_i$ of the simplicial chain group $C_{d}(R^d)$ (just triangulate them; WLOG, triangulations agree on the common boundary). Now, orient each $\Omega_i$ so that the induced orientations of the boundary are the same. Then the chain $c= c_1 - c_2$ is a cycle. If $\Omega_1\ne \Omega_2$, there is a point $p\in \Omega_1- \Omega_2$; then the intersection number between $c$ and the 0-cycle $p$ is $1$. Hence, $c$ defines a nonzero element of $H_d(R^d)$. But $R^d$ is contractible, so $H_d(R^d)=0$. A contradiction. Consider reading "Differential Topology" by Guillemin and Pollack.
Comment: Does *Differential Topology* contain a proof of the fact that $\Omega_i$ can be triangulated so as to share a common boundary?
Comment: @MonstrousMoonshine: No, it does not. But in fact, you do not need a triangulation: Guillemin and Pollack work without introducing singular homology. All what you need is no notice that there is an abstract smooth oriented manifold $Z$ obtained by  gluing copies $\Omega'_1, \Omega'_2$ of $\Omega_1, \Omega_2$ along their common boundary and a continuous map $f: Z\to R^n$ which sends $\Omega'_i\to\Omega_i$ and such that some point $p\in R^n$ lies in $f(\Omega_1')- f(\Omega_2')$.


Is Alfred Tarski's Introduction to Logic still helpful for self study?

Question: I am trying to setup a self study path to enhance my knowledge of mathematical logic.  I haven't taken a logic course for a few years and my confidence on mathematical proofs is unnerving.
I am planning to attend college in a year to study physics and would perfer not to sit idle when I could be learning on my own. (I perfer self study anyway.)
I am currently going through the following books:

The Feynman Lectures on Physics Vol. 1
Basic Mathematics by Serge Lang (Checking on anything I'm not solid on before attempting calculus which I've only slightly dipped into)
Godel, Escher, Bach: An Eternal Golden Braid

I would like to supplement this all with a refresher on logic and then perhaps a second course level book on mathematical logic.
I picked up Alfred Tarski's Introduction to Logic and so far it has been great however I don't see many people talking about it online.  It seems other books are more highly recommended especially in the "Teach Yourself Logic" pdf by Peter Smith.
I'm wondering if it would be a better use of my time to get a book that will be self sufficient as a preface to higher mathematical logic.  I wouldn't want to read through Tarski's book if there was another introductory book that presents the same material alongside more valuable information.
Or am I needlessly worrying?
Comment: If this question is about logic, why is it tagged under calculus and mathematical physics?
Comment: @AsafKaragila Sorry, this is my first question.  I have removed the offending tags.
Comment: If you want to be a physicist, studying a text book on mathematical logic would probably be a waste of time for you. For first year college science, I would recommend a good introductory book on calculus, another on Newtonian mechanics, maybe another on chemistry if that is a required course. Inquire at a physics forum.
Comment: It isn't a good idea to try reading the Feynman lectures if your math is at the level of Lang's *Basic Mathematics*. If you haven't yet learned calculus, and you want to learn some physics now, I'd suggest the PSSC textbook. Also, I wouldn't recommend studying mathematical logic at this point. People often wrongly believe that studying formal logic is going to help them argue mathematically. It is much more common for people to learn proofs by *doing* proofs - only later does it make sense to formalize things.
Answer: You won't be surprised to learn that in the last seventy-plus years since Tarski's book was first published in English, many other books have been appeared which will perhaps serve better as introductions to modern logic. And if you have downloaded my Teach Yourself Logic, you will have seen my "entry-level" suggestions on formal logic at the beginning of that Guide. And also my warm recommendation of Velleman's How to Prove It if you want to improve confidence in understanding modes of mathematical argument.
Still, Tarski's 1941 book is something of a classic -- a discursive and readable introduction at an elementary level to a range of topics in logic. If you are enjoying it, don't stop reading. It will teach you some important basic concepts in an accessible way. And at a pre-college level, it probably doesn't matter hugely what you read: finding things that you enjoy, that you are getting something out of, and that work well for self-study for you is more important. (After all, you are going to have years of the disciplined tread-mill of a fixed curriculum!)


Longevity of Tape versus Disk

Question: I read something in a Oracle Archiving book, about longevity of Tape Versus Disk, i quote:

"Longevity. No matter how you store your data, eventually it has to be
  moved either due to obsolescence or deterioration of the storage
  media. It is not uncommon for archive data to remain on tape for up to
  a decade (though the tape itself can last up to 30 years) — disk
  archives typically need to be replaced every three to five years."
Book: Archiving for dummies: Oracle special edition Page:18

Can a guru help me understand why disk life is less (as stated in the same source that Disks have 10 yrs of shelf life, comparing to the 30 yrs of Tape life)?
I would be thankful of the reading suggestion to understand this topic better. Thank you in advance.
[Waseem]
Answer: One reason is that a hard disk drive integrates far more drive components that can fail over time or from external sources of stress... For example, lubricants can turn into resins or vaporize (and to add insult to injury, sublimate onto and coat the media!), plastics can turn brittle, ESD can damage onboard electronics...
Also, if you gave me a 30 year old hard disk drive it would likely be ST506-connected (you would definitely have to find an ISA bus computer and the right controller card, different controllers formatted differently then!) and might even have a filesystem on it that would be difficult to mount with modern software. Finding handy hardware to connect a PATA or parallel SCSI drive to might start to be challenging in 5 years from now...
Comment: So are you saying if I gave you a 30 year old tape, it would be easier to source the needed tape hardware than the disk hardware? I think the flaw in the OP's interpretation of the quote is based on the idea of committing backups to a single media type/format *forever*.

Longevity of Tape versus Disk


Could not launch "" failed to get the task for process ?

Question: Using Xcode 4.5.2 and building for iOS4 or newer, I get this message when building for my device (iOS 6.0.1 on 4s).  I dismiss the dialog then relaunch the app on my device which seems to work.  I am newer to iOS development, so I aplogize in advance if this is a silly question.
Thank you in advance for your help.
Comment: possible duplicate of [xCode: failed to get the task for process](http://stackoverflow.com/questions/11601304/xcode-failed-to-get-the-task-for-process)
Comment: Is your run configuration set to debug?
Comment: Thank you, yes it was.  I changed it, still happening!?!  I am guessing a newbie mistake here....
Comment: http://stackoverflow.com/a/11601403/1059705
Answer: My issue was using Distribution provisioning profile for signing the app, once I made a development provisioning profile, the app installed and ran on iPhone just fine.
Comment: Perfect! Can someone please pass the message on to Apple, to allocate some budget to giving some useful error messages for stuff like this!?
Comment: Yes indeed: I was using an adhoc profile for debug in [Build Settings]->[Code Signing]... Switched to development profile, and could launch
Comment: Yayy this worked! So on code signing I changed the 2 Debug rows to "iPhone Developer" instead of "iPhone Distribution" which I had before. I didn't touch release.
Answer: The answer seems to be "you need to fix your provisioning profile", but can happen for several reasons, as indicated by other answers on here.
In my case, I hadn't added a new device to an existing developer provisioning profile, so I just re-created the profile with the new device, and it worked!
Answer: In my case happens all time I add a new device ID then update the provision profile, download and "install it on Xcode 5".
To fix this:

Go to Xcode>Preferences>Account Tab>Select Apple ID>View
Details>Refresh Button (Bottom left corner).
Reinitiate Xcode.

Start again the app, you will be able to test the app in the device.
Answer: Here's what my situation was and how I solved the problem:

I had been running the app from Xcode to my phone and all was fine
I switched to a different code signing identity  (I had to change the bundle name also to match)
I ran the app to my phone and got the error.  The app would install, but not open.
Did a bunch of stuff like Clean, close n open Xcode; delete the app from the phone. All to no good effect.

SOLUTION: turned the phone off n on.
Coincidence?  I think not.    :-)
Answer: XCode 6:
Just create provisioning profile for development and assing it to Project -> Build settings -> Provisioning profile
For upload you have to change provisioning profile for Distribution profile.


Conditional probability question for n trials`

Question: E and F are mutually exclusive events, trials are independent and performed repeatedly. I have already calculated the probability E or F occurs for the first time on the nth trial.
The question is:
What is the conditional probability that E occurs for the first time on the nth trial given that the event E or F occurs for the first time on the nth trial?
I think that the way this question is phrased, I can take as given that E or F occured for the first time on the nth trial, so my answer should intuitively be:
$\frac{P(E)}{P(E)+P(F)}$
But my friend is arguing that the probability of the event E or F occuring for the first time on the nth trial should be included in the conditional probability. I think he is right, but am confused about why my answer is wrong.
edit: Here is the verbatim phrasing:
What is the conditional probability that the event E occurs for the first time on the nth trial, given that
event $E \cup F$ occurs for the first time on the nth trial?
edit 2: alternate answer given is $\frac{(1-P(E))^{n-1}P(E}{(1-P(E)-P(F))^{n-1}(P(E)+P(F))}$ which I don't believe makes sense thinking about it more. For starters, why would adding uncertainty in the n-1 trials lead to my answer, which assumes these are determined, being multiplied by something larger than 1.
Comment: I think your answer is not wrong, One can use a longer  conditional probability calculation that uses the first time stuff. A related question was asked today, but the answer does not go into detail about the probability you ask about.
Comment: Is the condition, the event $E\cup F$ occurs for the first time on the $n$th trial, or is the condition that either $E$ occurs for the first time or $F$ occurs for the first time on the $n$th trial?
Comment: Kevin- i'm not sure I see how those are distinct? André, I guess this is where my question is, what is probabilistic about the first n-1 events? it seems from the wording this is determined
Comment: @qbert The first condition (which is what you edited in) is that neither $E$ nor $F$ occurs for the first $n-1$ trials, then one of them occurs on the $n$th trial. The second condition considers two possibilities- either $E$ does not occur for the first $n-1$ trials, but $F$ might, and $E$ occurs on the $n$th trial (this is $E$ occurs for the first time on the $n$th trial), or $F$ does not occur for the first $n-1$ trials, but $E$ might, and $F$ occurs on the $n$th trial (this is $F$ occurs on the $n$th trial). Whenever the first applies, the second does too, but not necessarily vice versa.
Comment: In my edit, i just replaced "or" with $\cup$ which is equivalent. I am not following the logic here
Answer: Let $E_i, F_i$ be the event that $E, F$ occurs in the $i$-th trial respectively, $i = 1, 2, \ldots, n$. Maybe your friend is considering this:
$$\begin{align} & P\left(E_n \Bigg| (E_n \cup F_n) \cap
\bigcap_{i=1}^{n-1} (E_i^c \cap F_i^c) \right) \\
=&~ \frac {\displaystyle
P\left(E_n \cap (E_n \cup F_n) \cap
\bigcap_{i=1}^{n-1} (E_i^c \cap F_i^c)\right)}
{\displaystyle P\left((E_n \cup F_n) \cap
\bigcap_{i=1}^{n-1} (E_i^c \cap F_i^c)\right) }
\end{align}$$
Assuming that performed repeatedly means that those trials are independent, this reduced to
$$ \frac {\displaystyle
P(E_n \cap (E_n \cup F_n)) \prod_{i=1}^{n-1} P(E_i^c \cap F_i^c)}
{\displaystyle P(E_n \cup F_n) \prod_{i=1}^{n-1} P(E_i^c \cap F_i^c) }
= \frac {P(E_n)} {P(E_n) + P(F_n)}
$$
Usually people familiar with this will know the independence and directly skip this.
Comment: Occur, not necessary to be the first time.
Comment: Do you mean $E_{i}$ is the probability it occurs for the first time on the ith trial?


"microsoft.visualbasic.fileio does not exist" trying to use TextFieldParser

Question: I've seen the above question asked many times on many sites, but I haven't seen an answer that fixed the problem.
The scenario is this...
I am on .NET Framework 4.0, building a C# web application in VisualStudio 2012 Express with the Razor view engine.
I'm trying to use Microsoft.VisualBasic.FileIO.TextFieldParser in my code. From what I've read it is appropriate to do so by adding a project reference to Microsoft.VisualBasic, which I've done, and coding @using Microsoft.VisualBasic; in my view. However when I code...
<code>Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(xxxxxxxx));
</code>
...in the view and rebuild the solution it returns errors: The type or namespace name 'FileIO' does not exist in the namespace 'Microsoft.VisualBasic' (are you missing an assembly reference?)
I know the reference is in the correct project because when I add and remove it I see it come and go from the references folder. I know the code I'm trying to reference exists because I can see it in Object Browser. I've even tried adding the reference using Object Browser instead of through the menus and although it gets added, the results are the same.
The solution it's in is a bit complicated so I tried just creating a test stand alone C# project and I get the same results. I also tried creating a test stand alone Visual Basic project, and sure enough, it works there as advertised. I'm by no means an expert on Visual Studio so I'm guessing that it's just something I'm missing in the configuration, but I'm at a loss to figure it out.
I've spent days on this, so any help anyone could offer would be greatly appreciated.
Comment: Do you see Microsoft.VisualBasic.dll under References folder in your project?
Comment: Did you add `Imports Microsoft.VisualBasic` to the code file?
Comment: Can you post a screenshot of your references for this specific project?  e.g. http://i.stack.imgur.com/bePc5.png
Comment: First time posting here so I'm not too familiar with how to respond but I'll give it a shot!
First to Tim - yes I did. Sorry but I showed @using in my original post which referred to a .cshtml page (which I also tried). Since the page I'm trying to get working is .aspx your comment was actually right on the money.
Comment: To eandersson - as I said I'm not a VS expert and I don't see a way to list references as you have in your attached capture. I've captured an image of my references folder if that helps... just not sure how to post it.
Comment: The reference shows as Microsoft.VisualBasic. Looking at the properties shows that it is Microsoft.VisualBasic.dll. So I would say yes.
Comment: I'm trying to post an image link using the syntax examples shown, but keep getting a message saying that the content is not allowed. Not sure what to do to get the image posted.
Comment: Okay, looks like new users cannot post pictures. Reasonable. So the reference capture is at... freeimagehosting-dot-net/rwtqq. Replace -dot- with a real dot to see the references.
Comment: Can you click on the reference in the solution explorer and see if it gives you a path to where the DLL is?  Maybe it's a location of the DLL issue (I rather doubt it, but it never hurts to rule out the simple stuff).
Comment: Now sure what I'm looking for here, but the path is C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Microsoft.VisualBasic.dll and there is an actual file there.
This is the same file referenced in the Visual Basic project that works.
Answer:
Right-click on your project and select Add Reference...
In the Reference Manager, expand Assemblies and select Framework. Then check the box for Microsoft.VisualBasic and click OK.

Credit goes to:
https://stackoverflow.com/a/17146200/2530360
I just had the same problem and your question title was more verbose so I figured it should have the answer inside.


Sending dynamic variables in sendgrid v3 body using postman

Question: I am trying to send the emails via Sendgrid using v3 API using postman, I have created 3 separate variables in 3 different requests, I want to pass all those 3 variables in a single mail, for that I have used below sendgrid
 https://api.sendgrid.com/v3/mail/send
with below body
{
  "personalizations": [
    {
      "to": [
        {
          "email": "email@example.com",
          "name": "API Testing"
        }
      ],
      "subject": "API testing successful"
    }
  ],
  "from": {
    "email": "firstname.lastname@example.com",
    "name": "API Testing"
  },
  "content": [
    {
      "type": "text/plain",
      "value": "{{variable1}}"  //In variable1 has a dynamic values
    }
  ]
}

but the above format sending the mail body as {{Variable1}}, can someone help me on this?
Comment: Can update the question with details about the variables being used and how you're setting this up in Postman. Feels like the question is missing half the details.
Comment: *I want to pass all those 3 variables in a single mail*  This is contradictory statement with the code shown in the question. What are these three variables? do you want to call a same request three times with a different data?
Answer: For handlebar {{ variable_value }} substitutions in dynamic HTML templates, u need to pass the variable value as JSON structure with the key as "dynamic_template_data" as part of personalizations.
U also need to pass the (API Key) Authorization  as "Authorization: and Value as "Bearer ".
In the Request Body pass the personalizations object.
{
"personalizations": [
    {
        "to": [
            {
                "email": "ron@***",
            }
        ],
        "dynamic_template_data": {
            "<variable_name>": <variable_value>
        }
    }
],
"from": {
    "email": "email@example.com",
    "name": "Development Team"
},
"content": [
    {
        "type": "text/html",
        "value": "replace body with template content"
    }
],
"template_id": "******"

}
Answer: From what I understand of the question you want to send multiple requests with different values.
Say, GET to https://google.com/q={{search}} and you have multiple search queries, (dog, chess, marvel, stackoverflow)

Create a collection in postman
Add a GET request to https://google.com/q={{search}} with necessary headers and hit Save
Create a CSV file with the header search and all search values under it
Hit the run button for the newly created collection
Set the Iterations field to the number of queries you have. In this example it is 4
Look for the field Data, select the created CSV file
Ensure the data is correctly being picked up by hitting the Preview button
Hit Run test
You can view the output in the Postman Console

To open Postman Console Head to View in the application menu, and click on "Show Postman Console" or use the keyboard shortcut (CMD/CTRL + ALT + C) to open.
Comment: Thanks for your comment @codeblooded, but that was not what I am looking for, I have found my answer by doing some trial and errors, I have created a variable in Globals in every request like **pm.globals.set("variable1", responseCode.code);** {This is for capturing response code in a variable} in Tests and pass that variable in the required body.


ajax modified form drop down doesn't save

Question: I have used form_alter to add a ajax callback to an element to my form. When the user chooses an option, it creates dropdown options for the other field. However, while this works fine for changing the form, it doesn't actually save the value in the field when you click save. I checked the database and its not saved, value is 0. Not exactly sure what is happening.
Here is my code:

/**
 *  Implements hook_form_alter().
 */
function chapter_sponsor_levels_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'sponsor_node_form') {
    //we need to add an ajax call to the OG Group field on the Sponsor node page, so that it populates the sponsor level dropdown
    $form['og_group_ref']['und'][0]['default']['#ajax'] = array(
      'callback' => 'chapter_sponsor_levels_update_levels',
      'wrapper' => 'edit-field-sponsor-level',
      'method' => 'replace',
    );
    if(!empty($form['og_group_ref']['und'][0]['default']['#default_value']) && empty($form_state['values'])) { //if we are viewing the form not from an ajax request
      dpm($form);
      dpm($form_state);
      $gid = $form['og_group_ref']['und'][0]['default']['#default_value'];
      chapter_sponsors_levels_set_levels($gid, $form);
      dpm($form_state);
    }
    elseif (!empty($form_state['values']['og_group_ref']['und'])) { //if we have chosen a group
      //$gid = 8; //new york
      $gid = $form_state['values']['og_group_ref']['und'][0]['target_id'];
      chapter_sponsors_levels_set_levels($gid, $form);
    }
    $form['#submit'][] = 'chapter_sponsor_levels_save_level';
  }
}

function chapter_sponsors_levels_set_levels($gid, &$form) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
    }
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}

EDIT: Forgot to add this in to the post

function chapter_sponsor_levels_save_level(&$form, &$form_state) {
  dpm($form_state);
}
/*
 * AJAX callback when click on OG Group field on Sponsor page
 */
function chapter_sponsor_levels_update_levels($form, $form_state) {
  return $form['field_sponsor_level']; //update the sponsor_level field with the new dropdown values
}

EDIT:
I may be getting closer, but not yet there. I realized that if its not saving the value, its proabably because it doesn't match a list of allowed values. While I didn't see such a constraint in the database, I found a 'allowed values' list in the $form_state array. I modified my code above:

foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][$name] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }

However, now when I try to save the form when choosing a value, it says that it is an illegal value. I found that it was throwing the error from line 397 in the list module - for some reason, its not passing the 'allowed values' test.
Comment: I am not seeing where the function `chapter_sponsor_levels_update_levels` is defined.
Comment: @Coleman - I just added it into the post
Comment: why have you got `und` in your form item? `$form['field_sponsor_level']['und']['#title']`
Comment: @2pha - I have an und because thats the arrary structure I see in the dpm of $form. It clearly is correct because the array is modified by the ajax request. My issue is that its not saving the form data.
Answer: Ok, I finally got it right, here's the code of the function which does the work:

function chapter_sponsors_levels_set_levels($gid, &$form, &$form_state) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }
    $form['field_sponsor_level']['und']['#default_value'] = $form_state['build_info']['args'][0]->field_sponsor_level['und'][0]['value'];
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}


How to implement jQuery Accordion for a Menu?

Question: I'm looking to implement something like the Accordion Menu module, but unfortunately that module has issues with Menu Block and other modules... so what's the best way to implement the jQuery Accordion menu with primary and secondary links, from a theming perspective? Should be a simple question for a themer, but I haven't found any specific tutorials that can take me step by step.
Using Drupal 7, Adaptive Theme.
update: thanks for all the responses. I'll look at all of the suggestions and provide another update :-)

Madam Adam's solution: not working correctly yet

Only got it to work with this modification; added to js file

(function ($) {
//add drupal 7 code
Drupal.behaviors.myfunction = {
    attach: function(context, settings) {
//end drupal calls

//some jquery goodness here...
$( "#accordion" ).accordion( {
  header: "li",
  collapsible: true
} );

}}})
(jQuery);

Comment: Whats the issue you are facing with accordion?
Answer: You have to include the accordion library by adding this line to your theme's template.php:
drupal_add_library('system', 'ui.accordion');

Then you trigger the accordion by adding this to yout template.php or an external js-file:
$( "#menu-container" ).accordion( {
  header: "li",
  collapsible: true
} );

Comment: ok so I finally got some type of accordion from jQuery using the following code:
Comment: added code and more info in post. Right now there is only one header and all other parent links are within the first parent link. Lets say I have 3 sibling links 1, 2, 3. Links 2 and 3 get nested within Link 1.  Maybe something wrong with my ID?
Answer: You can write a simple jQuery script to create accordion like menus

with little adjustment in css. Check classes in the image and how it is used in jQuery
Comment: wasn't able to get this to work at all.
Comment: I have updated it
Answer: I found flexnav to be extremely useful.  There is a module in development that makes most of the installation very easy,  can't recommend it enough.


checking, is user authenticated in mvc application, when local applications sends requests

Question: I have asp .net mvc application with authorization system. Console(or winforms, doesn't matter) application uses WebRequest to post some data to server. Everything is ok, but know I need check, is user authorized, and return it. So, I'm cheking
User.Identity.IsAuthenticated

and it returns false. But in browser I'm authenticated and this method obviosly works in mvc-aplication, but when console application sends requests, it doesn't work. How to solve it?
I'm using it to load my files
Answer: Essentially, your console application needs to also send the "forms authentication cookie or ticket" in the request to your web server. This post might be helpful http://www.codeproject.com/Articles/187198/Various-Clients-and-Forms-Authentication.
Answer: When you create your web request (I assume you mean an HttpWebRequest), make sure it's configured to send windows credentials.
For HttpWebRequest, you would set UseDefaultCredentials to true:

Set this property to true when requests made by this HttpWebRequest object should, if requested by the server, be authenticated using the credentials of the currently logged on user.
Comment: It doesn't work( I tried to make simple request to page, that writes just is user authenticated, but it returns false even if I set UseDefaultCredentials true..
Comment: I thing I have some server problem, because when I request vk.com it is authorized even without UseDefaultCredentials


Strange Decimal behavior while constructing from float literal

Question: I was expecting 2 decimal precission, but:
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 2
>>> Decimal(98791.4913)
Decimal('98791.491299999994225800037384033203125')
>>> getcontext()
Context(prec=2, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

Why is Decimal not honoring the Context precission?
Comment: From looking at https://docs.python.org/2/library/decimal.html, precision only affects the result of arithmetic operations. For example, with getcontext().prec = 2, the  result of Decimal(98791.4913)/1 is  Decimal('9.9E+4').
Answer: Quoting from documentation (Emphasis mine) -

If value is a float, the binary floating point value is losslessly converted to its exact decimal equivalent. This conversion can often require 53 or more digits of precision. For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').
The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, Decimal('3.00000') records all five zeros even if the context precision is only three.
The purpose of the context argument is determining what to do if value is a malformed string. If the context traps InvalidOperation, an exception is raised; otherwise, the constructor returns a new Decimal with the value of NaN.

And from same documentation -

The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic operations.

Great examples given in the documentation -
>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

Comment: The [quick-start tutorial](https://docs.python.org/2/library/decimal.html#quick-start-tutorial) on the same page says this more succinctly:  "The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic operations."  It also gives an example.
Comment: Thanks will add those to the answer.
Answer: From the documentation:

If value is a float, the binary floating point value is losslessly
  converted to its exact decimal equivalent. This conversion can often
  require 53 or more digits of precision. For example,
  Decimal(float('1.1')) converts to
  Decimal('1.100000000000000088817841970012523233890533447265625').
The context precision does not affect how many digits are stored. That
  is determined exclusively by the number of digits in value.
...
Context precision and rounding only come into play during arithmetic operations.

Emphasis mine.
You can truncate the value by using the Decimal.quantize method:
places = 2
Decimal(98791.4913).quantize(Decimal(10) ** -places) # 98791.49

or the Context.quantize:
places = 2
getcontext().quantize(Decimal(98791.4913), Decimal(10) ** -places) # 98791.49

Comment: @jeckyll2hide: 2 decimals is not the same as a precision of 2.  `98791.49` has a precision of 7.
Comment: That is a very weird method to get 2 decimals. I prefer `Decimal('%.2f' % 98791.4913)`, which is still not very pretty.


Spring data neo4j repositories not working since DATAGRAPH-939

Question: I'm using:
Spring-data-neo4j 4.2.0-SNAPSHOT (tried with 4.2.0.RC1 too)
and since the DATAGRAPH-939 commit, I'm not able to work with repositories anymore.
<code>@Repository
public interface MyEventRepository extends GraphRepository<Event> {}
</code>
The error:
<code>Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myEventRepository': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:735)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 41 common frames omitted
</code>
Here is an example of my failing test:
<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SimpleTest.TestConfiguration.class })
public class SimpleTest {

    @Configuration
    @EnableNeo4jRepositories("com.nagra.ml.sp.cpm.core.repositories.test")
    public static class TestConfiguration {

        @Bean
        public org.neo4j.ogm.config.Configuration configuration() {
            org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
        config  .driverConfiguration()
                .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
            return config;
        }

        @Bean
        public SessionFactory sessionFactory() {
            return new SessionFactory(configuration(), "com.nagra.ml.sp.cpm.model");
        }

        @Bean
        public Neo4jTransactionManager transactionManager() {
            return new Neo4jTransactionManager(sessionFactory());
        }
    }

    @Test
    public void test() {
        assertTrue(true);
    }
}
</code>
According to documentation, the way of declaring repositories seems to be correct, am I doing something wrong ?
Thanks
Comment: There was a maven repository error around the time you raise this issue. Have you tried again with `mvn -U`?
Comment: I've tried again with 4.2.0.RC1 and 4.2.0.BUILD-SNAPSHOT (-U), I still have the same problem.
Comment: OK. If you haven't raised a Github issue then maybe to that. I'll try and investigate this today.
Comment: Thanks. Opened here : https://github.com/spring-projects/spring-data-neo4j/issues/384
Comment: Moved here: https://jira.spring.io/browse/DATAGRAPH-950
Answer: I no longer have issues with repositories. I'm now using SDN 4.2.0.RELEASE with Spring boot 1.5.1 and I no longer extends GraphRepository as explained in SDN4.2.0 documentation.


Ping and mDNS over WireGuard not working

Question: When running through WireGuard VPN tunnel from outside the network, I can access machines inside directly via IP. For example, hitting IP of PiHole box in a browser returns the PiHole UI. I can also access the internet fine.
When issuing a ping command to that same IP address through WireGuard results in a "no route to host" error. Same applies to pinging the router's IP. When inside network on WiFi, running ping gets a response for both.
Ultimately trying to troubleshoot why mDNS packets aren't making it to and from the device on VPN. There's a mDNS reflector on the router, specifically enabled for WireGuard interface, so should be making it across the tunnel. The ping and mDNS issues could be related.
Where should I be looking to troubleshoot?
Comment: The ping could be blocked by a firewall: if the same IP destination works with TCP (HTTPS...) and not ICMP, This can't be a routing problem, or you didn't provide everything (like iptables/nftables port redirection etc.).
Comment: *Where should I be looking to troubleshoot?* - your wireguard configuration
Answer: Wireguard connections do not support multicast by default (you may be able to force it on after the link is created), so even with a mDNS reflector it's not going to see the mDNS requests over the tunnel.
EDIT:
You can enable it after the link is up, but it needs to be done at both ends e.g. with
<code>PostUp = ip l set wg0 multicast on
</code>


Proof of Jordan Curve Theorem for Polygons

Question: So I'm trying to prove the Jordan curve theorem for polygons, but I'm not sure how to show that a line segment that does not intersect the boundary has all points of the same parity.  I'm also not sure how to show that all the external points are connected by a polygonal path and all the internal points are connected by a polygonal path.
Answer: Here is a paper which explain the Jordan curve theorem for polygons.
Comment: It's very handwavy, what with all the "turning off just before" and "following along". In fact, the crucial part of any proof of the Jordan curve theorem for polygons involves such kind of path constructions.


Formula for normalizing data

Question: I have four groups of treated animals data, Wildtype age 3 months, Knock our age 3 months,  Wildtype age 6months, and Knockout age 6 months. I need to normalize all the data to the untreated  Wildtype age 3 months old. What is the best formula to use?
Comment: Welcome to this forum! Consider taking a tour: https://stats.stackexchange.com/tour . Hope this will help!
Answer: Say you have some variable X ranging from 1 to n, so $\{x_1 , \dots x_n\}$.
If you want to normalize your data (which i presume for you means making it between 0 and 1) then you simply do the following:
$$y_i = \frac{x_i-min(X)}{max(X) - min(X)}$$
And Y will be your new normalized variable.
Maybe you want it to have mean 0 and standard deviation 1 in which case you can do:
$$y_i = \frac{x_i - \bar{x}}{\sigma}$$
Where $\bar{x}$ is the mean of X and $\sigma$ is the standard deviation of X
Comment: Thanks rannoudanames. I am still confused. In the two formulas you mentioned above, which symbol represents the control that I should normilzed my data to?

Formula for normalizing data


A diferença entre req.params e req.query

Question: Estou com uma dúvida sobre parâmetros de url. É o seguinte, eu sei que tem como eu resgatar um parâmetro dessa forma users/:id, ai nisso eu resgato com o req.params.id, mas vi um vídeo que o cara utilizou esse modo, req.query e nesse req.query ele colocou dentro de uma variável, e todos os parâmetros que ele passou via url ele conseguiu resgatar.
A minha dúvida é: qual a diferença deles? E em qual contexto devo usá-los??
Answer: Edgar, pelo que conheço, o params são os parâmetro da URL do seu endpoint, enquanto o query, são os parâmetro enviados após o interrogação(?).
Por exemplo, nessa URL, ficaria dessa forma:
http://www.test.com/xpto/?xisto=1
params : xpto
query : xisto=1
Comment: Se estiver usando express, essa documentação deles é bem legal:
http://expressjs.com/en/api.html
Answer: Normalmente os parâmetros query são utilizado para consultas/filtro.
Por exemplo vamos supor que a sua aplicação trabalhe com empresas e funcionários.
Poderíamos ter a seguinte rota:
GET /empresas/1/funcionarios ( retornaria todos os funcionários da empresa 1 )
GET /empresas/1/funcionarios?ativos=true ( retornaria todos os funcionários da empresa 1 que estão ativos )
Answer: O params vem da Url quando ela tem dois pontos, normalmente é usado para IDs, para acessar um item especifico do seu banco, por exemplo:
No Backend, http://www.meusite.com.br/users/:id, assim você cria um endpoint para acessar um usuário em especifico baseado no seu id.
Então no front http://www.meusite.com.br/users, acessando o usuário de id = 1.

O query também pode vir da Url, após a '?', normalmente é utilizado para filtros em pesquisas no banco, por exemplo:
No Backend, http://www.meusite.com.br/users e cria os acessos req.query.status, req.query.idade, req.query.outros.
Então no front acessa o endpoint dessa maneira http://www.meusite.com.br/users?status=ativos&idade=30, filtrando pelos usuários que tem o status ativo e igual igual a 30, ou você pode tratar para que seja idades maiores que 30 ou menor, vai da logica feita no backend e não se esqueça de documentar para que fica de facil entendimento dos filtros que podem ser usados.


unlink function is not working

Question: I'm using the following code.
     $un=@unlink('/var/www/vhosts/mtsbeta.com/httpdocs/beta/cache_files/cache.php');
    print_r($unlink);
    @session_destroy();
    //exit;
    $host1=$_SERVER['HTTP_HOST'];
    header("location:https://$host1/index.php?msg=2");

if I used the exit it is working.please let me know why it is not working?
Comment: What isn't working?  The `header` *won't* work because you are `print_r`ing before it.
Comment: Try removing the `@` before `unlink`.  If you are trying to debug a script, hiding the errors isn't going to help.
Comment: Maybe your index regenerates the cache.php?
Comment: unlink function is not working .header is working
Comment: Have you tried removing the `@` so that you can see *why*?
Comment: I removed the @ it is not working.if I put the exit and refresh the page then it is working why?
Answer: lots of issues in the posted code:
@unlink('/var/www/vhosts/mtsbeta.com/httpdocs/beta/cache_files/cache.php');

--Remove the @ symbol as the others suggested, it will throw the error message
print_r($unlink);

-- There is no variable called $unlink in the code. What you have is $un Also the return value of unlink() is either true or false, not an array. So when you do a print_r, you either get 1 (in case of true/unlink success) or nothing at all (in case of false/unlink failure) - and this might even further confuse you.
header("location:https://$host1/index.php?msg=2");

-- you are already doing a print_r. If anything has been outputted into the page, then header wont work
I know this is not an answer to the OP question, but I think considering there are at least three desired changes in five lines of working code, maybe tweak the code a bit more before getting into the issue with the unlink not working?
Comment: i removed the @ it is not working not showing the any error and it redirecting the page to the index.php
Comment: There can be a bunch of things. First, how are you determining that the file is not getting deleted? are you checking its location physically? what process created the file? does your process have write permission over it?

First thing to do is to comment out the header() and start debugging. We are in no hurry to jump to another page before we are sure the file has been deleted, right? :)

unlink function is not working


Optimização de funções PHP para querys à base de dados

Question: Muitas vezes vejo funções diferentes em PHP para cada query. Gostava de saber se existe algum senão em fazer o seguinte, numa conexão com PDO:
function get_user_data($table, $columm, $required) {

  $db = conn();
  $data = array(':value' => $required);

  $sql = ("SELECT * FROM {$table} WHERE {$columm} = :value");
  $result = $db->prepare($sql);
  $result->execute($data);

  $result->rowCount();
  return $result->fetchAll(PDO::FETCH_ASSOC);

}

Desta maneira só temos de fazer uma função PHP para query de seleção, alterando só os argumentos consoante as necessidades.
Sendo assim (não havendo senão neste design) até poderíamos ir mais longe?
function update_tables($table, $collum1, $value, $collum2, $id) {

  $db = conn();
  $data = array(':value' => $value, ':id' => $id,);

  $sql = ("UPDATE {$table} SET {$collum1} = :value WHERE {$collum2} = :id");
  $result = $db->prepare($sql);
  $result->execute($data);

}

Comment: Miguel se a *query* de seleção for simples assim funciona perfeitamente. Mas e se precisares de um `INNER JOIN` por exemplo?
Comment: Eu tenho sempre dificuldades em fazer uma função de seleção generalista. Já de inserção e de atualização já consigo facilmente. Embora sejam um bocadinho mais complexas que estas, uma vez que podem receber um *array* de colunas e de dados.
Comment: Nesse caso, a de `INNER JOIN`, faria à parte. Podes dar um exemplo dessas funções mais complexas sff?
Comment: Miguel tens ai o meu exemplo, mas com `myslqi_`
Answer: Não existe qualquer problema no que indica, a implementação depende muito de cada um sendo que resulte no final numa chamada dentro das regras do PDO.
Claro que depende também muito do projecto, e para cada um teremos certamente abordagens diferentes. Eu prefiro quase sempre... ok... sempre... a utilização OOP/classes e objectos e quando implementamos qualquer modelo é essencial a sua utilização hoje em dia. Também é importante a semântica utilizada.
Mais uma vez, não sendo a melhor forma pelos motivos que expliquei, vou passar a responder dentro do modelo da pergunta no sentido de o levar a pensar de outra forma, assim e no seu caso específico da função update_tables faria o seguinte:
function update_table($table, $collum, $id, $value) {

  $db = conn();
  $data = array(':value' => $value, ':id' => $id,);

  $sql = ("UPDATE {$table} SET {$collum} = :value WHERE `id` = :id");
  try {
       $st = $db->prepare($sql);
       $st->execute($data);
       return true;
    } catch (PDOException $e) {
       return false;
    }

}

As implementações pode variar, mas o que apresento aqui vai no sentido de explicar o seguinte:

o nome do método update_table poderá ser outro pois é importante reduzir a escrita sempre que possível mas torná-la lógica dentro do contexto. Tratar-se-á sempre de um UPDATE à TABLE neste caso.
A mudança do $id também é importante pois o conceito tem ordens tabela > coluna depois virá o identificador, etc.
adicionar algum valor acrescentado à função também é importante. Saber, por exemplo, se actualizou bem ou se sequer actualizou... para o efeito basta retornar true ou false. Encapsulando os possíveis erros que poderão acontecer também estamos a evitar muitos try e catch ao longo do projecto.
Num UPDATE é normal tentar perceber se atualizamos um ou mais itens mas isso depende da lógica requerida.

Faz todo o sentido a utilização de funções de forma a simplificar-mos a nossa vida enquanto programadores, mas quando o fazemos temos de o realizar de uma forma mais abrangente possível de forma a conseguirmos "quase" um texto que nos conte tudo quando lemos o nosso código.
É importante o contexto, a atribuição de nomes, a validação de possíveis erros e o retorno do resultado.
Terminando, dizer que relativamente ao código que se constrói para utilização ao longo de um projecto a documentação é essencial.
Comment: Muito bem respondido +1 Acho que a minha resposta poderá ser vista como um complemento a esta, como um exemplo.
Comment: @JorgeB. claramente. achei importante alguma explicação de forma a que o Miguel possa entender melhor o conceito.
Answer: Eu não uso PDO, uso mysqli_ mas de qualquer forma fica uma otimização de uma função de inserção ou atualização genérica:
/**
 * Insere dados numa tabela.
 *
 * @param string $table nome da tabela
 * @param array  $data field=>value
 * @param array  $format %i,%d,%s,%b (int, double, string, blob)
 * @return boolean retorna verdadeiro se inseriu, senão falso.
 *
 */
function insert( $table, $data, $format )
{

    $conn = connect();

    if ( empty( $table ) || empty( $data ) )
    {
        return false;
    }

    $data   = (array) $data;
    $format = (array) $format;

    $format = implode( '', $format );
    $format = str_replace( '%', '', $format );

    list( $fields, $placeholders, $values ) = prep_query( $data );

    array_unshift( $values, $format );

    $sql_insert = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders}) ON DUPLICATE KEY UPDATE ";

    $first = 1;
    foreach ( $data as $field => $item )
    {

        if( $first != 1 ) $sql_insert.=", ";
        $sql_insert.= "$field=VALUES($field)";
        $first = 0;
    }

    $stmt = $conn->prepare( $sql_insert );

    call_user_func_array( array($stmt, 'bind_param'), ref_values( $values ) );

    $stmt->execute();

    if ( $stmt->affected_rows || $stmt->insert_id )
    {
        return true;
    }

    return false;
}

/**
 * Pepara os campos de dados e respetivos valores.
 *
 * @param  $data
 * @return array
 */
function prep_query( $data )
{
    $fields       = '';
    $placeholders = '';
    $values       = array();

    foreach ( $data as $field => $value )
    {
        $fields  .= "{$field},";
        $values[] = $value;

        $placeholders .= '?,';
    }

    $fields       = substr( $fields, 0, -1 );
    $placeholders = substr( $placeholders, 0, -1 );
    return array($fields, $placeholders, $values);
}

/**
 * Referencia os valores para que estes possam ser alterados.
 *
 * @param  $array
 * @return array
 */
function ref_values( $array )
{
    $refs = array();

    foreach ( $array as $key => $value )
    {
        $refs[$key] = &$array[$key];
    }

    return $refs;
}

Fica aqui um exemplo de utilização:
/*********************** exemplo de inserção de um user ************************

    $data   =
            array(
                'id'        => NULL,
                'name'      => "JorgeB.",
                'password'  => "1234"
            );

    $format = array('i','s','s');

    $table  = "users";

    insert($table, $data, $format);
*******************************************************************************/

Answer: Fazer esse tipo de funcionalidade na mão para mim é reinventar a roda.
Gosto de utilizar o Doctrine DBAL para trabalhar com a abstração de base de dados. Nele escrevo o código de uma vez somente e ele irá rodar independentemente do Banco de Dados ou do Driver de conexão (msqli, pdo).
Caso se interesse na documentação temos como utilizar essa biblioteca. Segue um exemplo de uma query mais avançada no query builder:
<?php

$conn = DriverManager::getConnection(array(/*..*/));
$queryBuilder = $conn->createQueryBuilder();

$queryBuilder
    ->select('u.id', 'u.name', 'p.number')
    ->from('users', 'u')
    ->innerJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id')

Além do SELECT ele incluí também INSERT e UPDATE, com uma sintaxe igual ao SQL.
<?php

$queryBuilder
    ->insert('users')
    ->setValue('name', '?')
    ->setValue('password', '?')
    ->setParameter(0, $username)
    ->setParameter(1, $password)
;

// INSERT INTO users (name, password) VALUES (?, ?)

$queryBuilder
    ->update('users', 'u')
    ->set('u.logins', 'u.logins + 1')
    ->set('u.last_login', '?')
    ->setParameter(0, $userInputLastLogin)
;

// UPDATE users SET u.logins = u.logins + 1, u.last_login = ?

A implementação de todos os métodos QueryBuilder você pode encontrar no GitHub.
Comment: Podes dar um exemplo de um `INSERT` e dum `UPDATE`?
Comment: Excelente, se pudesse dava +1 :D
Comment: +1 para o próximo projeto vou dar uma olhada nisso.


Estimator for $\theta$ using the method of moments

Question: Exercise :

Using the method of moments, find the estimator for $\theta$ for a random sample $X_1, \dots, X_n$ that follows the distribution with pdf $f(x) = \theta x^{-2}, \; 0 < \theta \leq x < \infty$, where $\theta$ is the unknown parameter.

Attempt :
$$m_1' = \bar{X}$$
$$μ_1' = \int_\theta^xu\theta u^{-2}\mathrm{d}u=\int_\theta^x\theta u^{-1}\mathrm{d}u=\big[\theta \ln u\big]_\theta^x =\theta\ln x - \theta\ln\theta$$
Thus, the estimator is given by :
$$m_1' = μ_1' \Rightarrow \theta\ln x - \theta\ln\theta = \bar{X}$$
But we cannot solve that equation with respect to $\theta$, so we'll take the moments of bigger order :
$$m_2' = \frac{1}{n}\sum_{i=1}^nX_i^2$$
$$μ_2' = \int_\theta^x u^2 \theta u^{-2} \mathrm{d}u = \int_\theta^x \theta \mathrm{d}u = \big[\theta u\big]_\theta^x =\theta x - \theta ^2 $$
Thus the solution of the following quadratic equation for $\theta >0$, gives as the estimator of $\theta$ :
$$\theta^2-x\theta +\frac{1}{n}\sum_{i=1}^nX_i^2$$
Question : Is my solution correct ? Shall the upper bound be $x$ or $\infty$ ?
Answer: The upper bound must be $\infty$. That is a real problem since we have :
$$\int_{\theta}^A xf(x)dx\underset{A\to \infty}\to \infty.$$
Then every moment of order greater than $1$ does not exists.
One way to estimate $\theta$ is to proceed as follows :
$$E(1/X)=\int_\theta^{\infty}  \theta x^{-3} dx=\frac 1 {2 \theta}.$$
Since, by LLN :
$$\frac 1 n \sum_{i=1}^n \frac 1 {X_i} \to E(1/X)=\frac1{2 \theta}.$$
We deduce :
$$\frac 2 n \sum_{i=1}^n \frac 1 {X_i} \to \frac 1 \theta.$$


Same note in two staves

Question: I have only just started to learn (on my own) to read music and play the piano at the grand old age of 64! Please can someone tell me how to play the same note on two staves? I keep being asked to play middle C with both the left hand and the right hand at exactly the same time. How?
Many thanks.
Comment: Congrats on starting to play music!  You are doing a great thing.  Is there any way you would be able to show us the excerpt?  This would help create more helpful / accurate answers.
Comment: Yes, there are a variety of things this *could* mean depending on what the context is; without seeing the excerpt, I'm not sure a definitive answer is possible. (That said, you should really consider all fingering as *optional*; all that matters is the sounds you produce, regardless of which fingering you use. So do whatever is comfortable and allows you to produce a good sound.)
Comment: One way to show us would be to scan in the section of music and then add the image to your question using the image button above the editing area. It seems an odd thing. Are you sure it's simultaneously with each hand, not one hand after the other?
Comment: +1 on Luke's duplicate; [Raskolnikov's answer](http://music.stackexchange.com/a/4686/2125) even has video of a pianist's hands demonstrating this overlap in Satie's Gymnopédie. Note that it may not be a duplicate though, depending on what Mig mean's by "same note". If it's 'same pitch with different durations' then they are duplicates, if it's 'same pitch and same duration' then this question is different.
Comment: This question contains "How?" It should also contain "Why?" Looking at the answers so far, Mig, please post the example.
Comment: Regarding the duplicate -  Gymnopedie isn't really a beginner's piece, so wouldn't be played by a raw learner. The held note taken over by the right hand could probably have been held with a sostenuto pedal. "At exactly the same time " is not how Satie wrote this.It would have been good to see the sample.
Comment: @dumbledad: Another possibility is different durations, but *starting* at the same time (rather than overlapping).  In that situation, the shorter note should often be performed as a rest (i.e. whichever hand has the longer note should be the one to play it), whereas in the linked scenario the hand with the longer note should play it; the later-arriving shorter note might be played with either hand as convenient.
Answer: I wouldn't bother trying to play the same note with left and right hands,simultaneously, it will sound just as good played by just one or the other. Without seeing the music, it's difficult to understand why you're being asked to do this - and quite unusual.for beginners, the 'cross-over ' point for each hand is often middle C, with it being played either with left thumb if it's written in the bass clef, or with right thumb if it's written in treble clef. As jjmusicnotes asked, a sample would allow us to help better. I echo the congratulations - it's never too late, but have an occasional lesson, so's you don't develop bad habits on the way. You won't regret it, with a good tutor.
     This may sound strange, but you are actually trying to learn two skills simultaneously - reading music, and finding your way round the keys. They are completely separate skills, only related by the music you make. Initially, just get to know the black and white bits on the piano, and how they relate to each other, sonically, not neccessarily thinking"this is an F and this is an A, and they sound good together, " but just geographically messing about with patterns. Sorry for the protracted answer, hope it helps.
Comment: dumbledad, that is what the question is about !  No, I don't see why one would need to do this, but that is what the OP posted, I think.
Comment: I don't understand this answer. When you say that a piano note will sound "just as good played by just one [hand] or the other" as played with the "left and right hands simultaneously" it implies that you can play a piano note with both hands simultaneously. But as each note has only one key this makes no sense to me. Do you mean press the one key down with a digit from both hands at once?
Comment: Indeed, though I was hoping that an answer might shed light on "why", but don't worry, [@AsianSquirel's answer](http://music.stackexchange.com/a/10824/2125) did just that :-)
Answer: When the score indicates the same note played twice simultaneously, and it's not a mistake, it means one of two things:

The doubling is intended to indicate something about the flow of the bass and melodic lines.  Both hands may be progressing towards the same note, and the composer might have wanted to call that out explicitly.  This might influence how you emphasize the note and the dynamics of the progression.
The score is not purely for piano, and two voices or instruments are intended to sing or play the same note.  This it very similar to the first point — you have separate things that are reaching the same common point.  On the piano, you are unifying these mutiple voices into one.

In both cases, Tim has it right; you do not play the note twice nor do you try to fit multiple fingers on the key.  Besides being awkward, you can't accomplish anything with two fingers on the same key than you can't with just one.  Playing it with one hand may be more obviously natural, so you should do so.  If not, simply pick which hand you would prefer to play it.
Comment: I've encountered a few cases where a note which started when the right hand was busy, was sustained while the left hand would be busy, and found the best solution was to start the note with one hand and hold it with the other.  In general, though, I'd agree that multiple fingers on a key would not be helpful.
Answer: I had to do this once, many many years ago when I was still taking lessons. I remember that was back when both hands were stationary (in the same position all the time) and middle c was like the "home keys" in typing, the key I anchored to. I'm guessing you're getting some kind of piano instruction so I suggest that, if you haven't already, you bring up your confusion with your teacher.
To use both thumbs to play middle c at once you should use one thumb to press half of the key and the other to press the other half (so they each scoot over to make room for the other, to "share" the key). As you've stated, this should be done simultaneously but as long as neither thumb is early it won't matter (if one thumb is slightly behind an on-time thumb, it won't affect the sound).
Hopefully this helps!
Comment: No, no form of playing the same key at the same time with two fingers should ever be done.  It's purposeless.  Pick one and use it.
Comment: Matthew - even as a beginners technique to establish a home position for the thumbs?
Comment: @dumbledad ESPECIALLY as a beginner's technique.  There's no reason to learn bad habits.  AsianSquirrel: Avoiding the upper parts of the keys is a terrible habit that I go to great lengths to break my students of. If it seems that your hands are too small (i.e. your fingers are too short) to reach further back on the key, then your hand should be further in. This shouldn't require contortion at all.
Comment: Do you mean you divided the key up laterally so that the thumbs were next to each other? This seems like an awkward solution at best and a literally impossible solution if your thumbs are too big. DON'T do this! Instead, one thumb should be further in on the key, i.e., further away from your body.
Comment: @KyleStrand I don't know; it's honestly just what my teacher told me to do. Also, I was probably about seven. I didn't do it for long and I wouldn't consider doing it now, but for a few weeks it was what I did. (And if you have small hands, trying to reach _up_ a key is awkward sometimes. And piano keys narrow down farther up the key so greater accuracy is necessary there...AND if your right hand was being used as the "contorted to reach higher" hand, you would be more likely to accidentally strike D#. [I'm right-handed --just controlling my left hand was enough of a challenge already!])

Same note in two staves


Migrating a huge live drupal 6 site to drupal 7 Server

Question: I am having a drupal 6 based news site with almost 600 thousand nodes. We are currently building a new site on drupal7.

What are the ways to migrate the content from old to new?
What are the best practices?
What are the know issues?
Can data be migrated in chunks?

I did alot of reading online, didn't find anything to give me confidence. Hopefully there will be people here who have hands on experience in this.
Comment: I've done a lot of data migrations into Drupal and each one was very different. Maybe there's a better way, but I would approach it by writing a D7 module to import data from the d6 instance. Yeap, manual queries to the old database, creating and saving node objects with the drupal api in the new system. Make a field for the old node ID in case you have any problems down the road so you don't have to start over if you end up missing anything.
Answer: This topic is already well covered in the Drupal documentation.


Django - Link to download CSV in template

Question: Trying to figure out how to correctly create a download link to a csv file on my template.
Views.py
#this is the view that shows the html page (all queries work)
def admin_view(request, mysite):
    context = dict()
    context["mysite"] = mysite.upper()
    group = whid.lower() + "-group"
    user = request.user.get_username()
    authorized = is_authorized(user, group)
    end_time = timezone.now()
    start_time = end_time.replace(day=1, hour=00, minute=00, second=00)
    error_message = ("You are not authorized to be in this page.")
    context['data'] = CheckIn.objects.filter(Date__range=(start_time, end_time))
    today = datetime.datetime.now()
    context['today'] = today
    context['first_day'] = today.replace(day=1, hour=00, minute=1)

    #Calling the csv function here
    context['response'] = export_search_csv(start_time, end_time)

    if (authorized):
        return render(request, 'mykiosk/admin.html', context)
    else:
        return HttpResponse(error)

#function to grab and create csv
def export_search_csv(start_time, end_time):
    data = CheckIn.objects.filter(Date__range=(start_time, end_time))
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="export.csv"'
    writer = csv.writer(response)
    writer.writerow(['id', 'EmpID', 'BarID', 'Username', 'Type', 'Liability', 'Date'])
    for item in data:
        writer.writerow([item.id, item.EmpID, item.BarID, item.Username, item.Type, item.Liability, item.Date])
    return response

Template
export to csv

Then all I get is a <HttpResponse status_code=200, "text/csv"> when trying to access the link. I'm missing something, I'm just not sure what. Due to internal company regulations, I can't use the djqscsv library either.
Any help is appreciated.
Answer: I think you are doing it wrong way. Rather than sending it via context, you should convert your export_search_csv method to a view and use it from template. For example:
def export_search_csv(request, start_date, end_date):
    data = CheckIn.objects.filter(Date__range=(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S"), datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")))
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="export.csv"'
    writer = csv.writer(response)
    writer.writerow(['id', 'EmpID', 'BarID', 'Username', 'Type', 'Liability', 'Date'])
    for item in data:
        writer.writerow([item.id, item.EmpID, item.BarID, item.Username, item.Type, item.Liability, item.Date])
    return response

def admin_view(request, mysite):
    ...
    context['start_date'] = startdate.strftime("%Y-%m-%d %H:%M:%S")
    context['end_date'] = enddate.strftime("%Y-%m-%d %H:%M:%S")
    ...

In template:
export to csv

Add new url for new view:
path('your_path/<str:start_date>/<str:end_date>/', export_search_csv, name='export_search_csv'),

Comment: this is smart. I used same logic to pass an args to a function in order to dynamically create many csv export without duplicating anything in views.py


SQL Count function inside an insert command

Question: I want to set the value of one of the fields with a number that is derived from a count function. But How do I do that?
    StringBuilder insertCommand = new StringBuilder();
 insertCommand.Append("INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed,Views,Replies,PageNumber)");
    insertCommand.Append("VALUES(@uniqueIdentifier,@TopicsID,GETDATE(),@questionTitle,@questionParagraph,0,0,0,@pageNumber)");

To set the page number parameter i want to do something like this:
    sqlCommand.Parameters.Add("@subTopic", SqlDbType.Int);
    sqlCommand.Parameters["@subTopic"].Value = "Count(ThreadID)/20";

I want to input a number that is divisible by 20 into PageNumber field in table Threads.
Note: The number should be a whole number.. so instead of returning 10/20=0.5, it should return 0.
Answer: You can use a query insert, like this:
INSERT INTO Threads (UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,
  ThreadClosed,Views,Replies,PageNumber)
SELECT @uniqueIdentifier,@TopicsID,GETDATE(),@questionTitle,
  @questionParagraph,0,0,0,FLOOR(Count(ThreadID)/20)
FROM table

Assuming the subtopic parameter name was a typo and you actually meant pagenumber. You never know though!
Comment: Well you said you want 0 instead of 0.5. That's what `FLOOR` does.
Comment: The problem now is that it doesnt recoginize the ThreadID , which is a primary key, and increments. Thats because threadID is a uniqueIdentifier. I set the whole thing to TopicID. FLOOR(Count(@TopicsID)... but it gives me 1. (TopicID is an auto incremental int, in the Topic table that is connected to ThreadsTable. They both increase together...Why i dont get the real count of TopicID. It is 6, but when i extract it it is 1.  :(
Comment: I corrected the mistake. I simply used inner join, to get the TopicsID in the Topics table. Thanks for the help


SPSS finding the significands between age_group and primary device of choice?

Question: I am trying to find a correlation between age group and primary device of choice, and then also compute a statistical significant.
Here's my output in SPSS,

I have grouped the data in this way:

This grouping isn't random, it was made this way, because I conducted an online questionnaire, where respondents were free to select their age group, instead of sharing their age directly. Now, if this was a mistake, it is too late to go back and email out to 50 people and ask them to redo the questionnaire.
What can be done for this to work and make sense?
Answer: It looks like you have 40 cases, where 22 have desktop as primary device and 18 have mobile as primary device, and that you've set up the data with three variables. What you want is two variables, age (group) and primary device, with two values for the primary device variable, one value for those with desktop as primary device, another for those with mobile as primary device. Then you can correlate the two variables. The CROSSTABS procedure (Analyze>Descriptive Statistics>Crosstabs in the menus) produces a variety of measures of association and correlation for such data.


How to save Venn diagram as PNG in python venn

Question: https://github.com/LankyCyril/pyvenn/blob/master/pyvenn-demo.ipynb
in this library, I want to know How to save Venn diagram as PNG
I knew the way how to save Venn diagram as PNG in matplotlib_venn
But, I don't know that way in Venn
I want to save the venn diagram as PNG
please help me...
Answer: <code>import matplotlib.pyplot as plt
from venn import venn
%matplotlib inline

musicians = {
    "Members of The Beatles": {"Paul McCartney", "John Lennon", "George Harrison", "Ringo Starr"},
    "Guitarists": {"John Lennon", "George Harrison", "Jimi Hendrix", "Eric Clapton", "Carlos Santana"},
    "Played at Woodstock": {"Jimi Hendrix", "Carlos Santana", "Keith Moon"}
}
# Save the figure
venn(musicians).get_figure().savefig("output.png")
</code>
Comment: Thank you
you are my angel !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


Getting Infinite Loop For Certain Inputs

Question: Working on an exercise using binary search to arrive at an answer to a credit card payment problem. I thought I had rock solid (albeit I'm sure elementary) code, that works for the example inputs, however the check is returning an infinite loop. I've tried about 20 different inputs for Balance, and all came back correct, until plugging in Balance = 2000, then it threw the infinite loop. I cannot figure out why. Any help is greatly appreciated Here is my code:
balance = 2000
annualInterestRate = .18
monthlyInterestRate = annualInterestRate / 12.0
lower_bound = balance / 12.0
upper_bound = (balance * (1 + monthlyInterestRate) ** 12) / 12.0
monthly_payment = (lower_bound + upper_bound) / 2.0
new_balance = balance

while new_balance != 0:
    monthly_payment = (lower_bound + upper_bound) / 2.0
    new_balance = balance
    month = 0

    while month < 12 and new_balance != 0:

        month += 1
        new_balance = new_balance - monthly_payment
        new_balance = new_balance + (new_balance * monthlyInterestRate)
        new_balance = round(new_balance,2)

    if new_balance < 0:
        upper_bound = monthly_payment

    else:
        lower_bound = monthly_payment

print "Lowest Payment:", round(monthly_payment,2)

Answer: Rounding error: new_balance ends up 0.01. You probably want to check that lower_bound and upper_bound are still not equal in the while condition.
Answer: I notice that the new_balance can become negative. If that is the case, then it will never fall out ot the main loop. put in a debug test
if new_balance < 0:
  raise ValueError

You can put in a print in the except or just use that to check. Alternatively, change the while to
while new_balance > 0:

Additionally, check that new_balance is not < .01 before the round. In fact, I would never allow a round up, but would always round down.
Also after having run a quick check, I saw a print out of new_balance after the round giving results of
.01
1846.64
1690.98

and the loop continues down to .01 again and around.


Angular JS - Call a Directive function in an outside Controller

Question: I am newbie in Angular JS, so probably my issue is quite simple, but actually I haven't found a solution for it.
I would like to know if it is possible to access a function (inside the link function in a directive) from an external controller. I am working with a Directive that control some variables required for the directive, and I need to access one of the from the controller. I was trying to create a function in the directive as:
<code>    scope.testArray = [{id=1, text="test1"},{id=2, text="test2"}];
    scope.getTestArray = function () {
          return scope.testArray()
    };
</code>
And from my controller I want to call it like this:
<code>    var testArray = scope.getTestArray()
</code>
But it says that the getTestArray does not exists for the element (scope). I assumed this is because the changes over the scope variable inside the directive, are not visible from the controller. So, Is there a way to achieve what I am trying to do?
Thanks for the help you can give me
Comment: directives are designed to implement DOM specific functionality.  for example ng-repeat repeats a particular chunk of html with dynamic data.  Are you sure you shouldnt be using a service instead?  I need a bit more context that your example code to give a specific answer
Comment: Why are you using a function? You can simply do `var testArray = $scope.testArray;`
Comment: I Agree with Codezille. Make use of two way binding. In the directive use the '=' symbol. This way you can modify the array inside and outise your directive and both parties share the same object.
Comment: @Anton I have read about the services, and maybe I will consider them. What I am trying to do is get the value of that array that is modified in the directive, in my controller. But it seems that what I'm doing is kinda overrating (to no say completely wrong)
Comment: @Codezilla Yes. Actually this works! It is better in this way ! Thanks. I forgot to define the variable in the directive. I was first, defining it in the Controller, but the idea is just get the value that the directive is handling. That is why it always says undefined.. Thanks for the info!
Answer: You controller gets instantiated before the directive gets loaded. You can simply delay the call to the directive function by doing:
<code>$timeout(function(){
    var testArray = $scope.getTestArray()
},1000);
</code>
Or you dont need to wrap it in a function. Simply do this:
<code>$timeout(function(){
    var testArray = $scope.testArray;
},1000);
</code>
Comment: you are probably right on the instantiating.  but that is kinda like the symptom rather than the actual problem
Comment: You can also use $evalAsync() instead of $timeout: http://stackoverflow.com/a/17795815/215945


Prove that $\lim_{x \to 0} \frac{f(x)}{x}=0$

Question: Problem: Given $\lim_{x \to 0} f(x) =0$ and $\lim_{x \to 0} \frac{f(2x)-f(x)}{x}=0$.
Prove that $\lim_{x \to 0} \frac{f(x)}{x} =0 $.
I observed that just proving that $\lim_{x \to 0} \frac{f(x)}{x}$ exists will finish the problem. But I am unable to do that.
Also, from the hypothesis we get that, for every $\epsilon > 0$ there exists a $\delta$ such that whenever $|x| < \delta $, we have
$\frac{|f(x)|}{|x|} < \frac{\epsilon}{|x|}$ AND $\lim_{x \to 0} \frac{f(2x)-f(x)}{x} < \epsilon$
Now adding the last two inequalities applying the triangle inequality, we get
$\frac{|f(2x)|}{|2x|} < 2\epsilon({1+\frac{1}{|x|}})$.
But i could not proceed.
Please help me with this problem.
Comment: $f(x)\not\leq\frac{f(x)}{x}$.
Comment: @Element118, yes. I will delete that  part.
Answer: Apply telescoping sums to the values at $x,x/2,x/4,x/8,x/16,…$.
And use that for $|x|<δ$ you get $|f(x)-f(x/2)|<ϵ·|x|$.
Comment: You need to get from $x$ to $0$ and the given identity provides argument doubling/halving. This invites to consider $f(x)-f(2^{-N}x)=\sum_{k=0}^{N-1}f(2^{-k}x)-f(2^{-k-1}x)$
Comment: Ah! got it. But what is the motivation behind this idea.?