Unexpected token. You may need an appropriate loader to handle this file type. book?.img ? /*#__PURE__*/React.createElement("img",

Question: When I run npm start command I get this error:
Failed to compile.

./src/layouts/BookCheckoutPage/BookCheckoutPage.tsx 131:10

Module parse failed: Unexpected token (131:10)

You may need an appropriate loader to handle this file type.

|       columnNumber: 21
|     }
>   }, book?.img ? /*#__PURE__*/React.createElement("img", {
|     src: book?.img,
|     width: "226",

This is my BookCheckoutPage.tsx file:
import React from "react";
import { useEffect, useState } from "react";
import BookModel from "../../models/BookModel";
import { SpinnerLoading } from "../Utils/SpinnerLoading";

export const BookCheckoutPage = () => {

    const [book, setBook] = useState<BookModel>();
    const [isLoading, setIsLoading] = useState(true);
    const [httpError, setHttpError] = useState(null);

    const bookId = (window.location.pathname).split('/')[2];

    useEffect(() => {
        const fetchBook = async () => {
            const baseUrl: string = `http://localhost:8080/api/books/${bookId}`;

            const response = await fetch(baseUrl);

            if (!response.ok) {
                throw new Error('Something went wrong!');
            }

            const responseJson = await response.json();

            const loadedBook: BookModel = {
                id: responseJson.id,
                title: responseJson.title,
                author: responseJson.author,
                description: responseJson.description,
                copies: responseJson.copies,
                copiesAvailable: responseJson.copiesAvailable,
                category: responseJson.category,
                img: responseJson.img,
            };

            setBook(loadedBook);
            setIsLoading(false);
        };
        fetchBook().catch((error: any) => {
            setIsLoading(false);
            setHttpError(error.message);
        })
    }, []);

    if (isLoading) {
        return (
            <SpinnerLoading />
        )
    }

    if (httpError) {
        return (

{httpError}

        )
    }

    return (

                        {book?.img ?

                            :

                        }

{book?.title}

{book?.author}

{book?.description}

                    {book?.img ?

                        :

                    }

{book?.title}

{book?.author}

{book?.description}

    );
}

I searched the issue, and many posts suggested that is a typescript issue or a tsconfig issue, or requre() method issue. I am 100% sure that it's not about that because I already used something similar in my project and did not have any errors. For eg this "ReturnBook".
import React from 'react'
import BookModel from '../../models/BookModel'

export const ReturnBook: React.FC<{book: BookModel}> = (props) => {
  return (

        {props.book.img ?

          :

        }

{props.book.title}

{props.book.author}

          Reserve

  )
}

Answer: Fixed it:
import React from "react";
import { useEffect, useState } from "react";
import BookModel from "../../models/BookModel";
import { SpinnerLoading } from "../Utils/SpinnerLoading";

export const BookCheckoutPage = () => {

    const [book, setBook] = useState<BookModel>();
    const [isLoading, setIsLoading] = useState(true);
    const [httpError, setHttpError] = useState(null);

    const bookId = (window.location.pathname).split('/')[2];

    useEffect(() => {
        const fetchBook = async () => {
            const baseUrl: string = `http://localhost:8080/api/books/${bookId}`;

            const response = await fetch(baseUrl);

            if (!response.ok) {
                throw new Error('Something went wrong!');
            }

            const responseJson = await response.json();

            const loadedBook: BookModel = {
                id: responseJson.id,
                title: responseJson.title,
                author: responseJson.author,
                description: responseJson.description,
                copies: responseJson.copies,
                copiesAvailable: responseJson.copiesAvailable,
                category: responseJson.category,
                img: responseJson.img,
            };

            setBook(loadedBook);
            setIsLoading(false);
        };
        fetchBook().catch((error: any) => {
            setIsLoading(false);
            setHttpError(error.message);
        })
    }, []);

    if (isLoading) {
        return (
            <SpinnerLoading />
        )
    }

    if (httpError) {
        return (

{httpError}

        )
    }

    return (

                        {typeof book !== 'undefined' && book.img ?

                            :

                        }

{typeof book !== 'undefined' && book.title}

{typeof book !== 'undefined' && book.author}

{typeof book !== 'undefined' && book.description}

                    {typeof book !== 'undefined' && book.img ?

                        :

                    }

{typeof book !== 'undefined' && book.title}

{typeof book !== 'undefined' && book.author}

{typeof book !== 'undefined' && book.description}

    );
}


How do nested replacement operators work?

Question: I was working with a list of lists today and needed to replace an element of one of the second-level lists. The way to do this seemed obvious, but I realized I wasn't actually clear on why it worked.
Here's an example:
a <- list(aa=list(aaa=1:10,bbb=11:20,ccc=21:30),bb=list(ddd=1:5))

Given this data structure, let's say I want to replace the 3rd element of the nested numeric vector aaa. I could do something like:
newvalue <- 100
a$aa$aaa[3] <- newvalue

Doing this seems obvious enough, but I couldn't explain to myself how this expression actually gets evaluated. Working with the quote function, I cobbled together some rough logic, along the lines of:
(1) Create and submit the top-level function call:
`<-`(a$aa$aaa[3],newvalue)

(2) Lazy evaluation of first argument in (1), call function '[':
`[`(a$aa$aaa,3)

(3) Proceed recursivley down:
`$`(a$aa,"aaa")

(4) ...further down, call '$' again:
`$`(a,"aa")

(5) With (4) returning an actual data structure, proceed back "up the stack" substituting the returned data structures until the actual assignment is made in (1).
I guess my confusion involves some aspects of lazy evaluation and/or evaluation environments. In the example above, I've simply reassigned one element of a vector. But how is it that R keeps track of where that vector is within the greater data structure?
Cheers
Comment: I wonder if this [Answer](http://stackoverflow.com/questions/6437769/why-does-item-assignment-in-non-existant-data-frame-column-work/6440706#6440706) might help?
Answer: I think a$aa$aaa[3] works as followed:
When you want to access an element still within the current object you use single square brackets, []. This makes the element accesible, but you can not perform complex manipulations with it because the element is still part of the object.
When you access the element using $, this translates from a$aa to a[["aa"]], thus releasing the element from the current object.
The total expression a$aa$aaa[3] translates to a[["aa"]][["aaa"]][3]. This is treated as a vector of vectors ->

Take object a, access vector aa.
Access vector aaa.
Access the third element in vector aaa.

The R evaluation:
 > a
 $aa
 $aa$aaa
 [1]  1  2  3  4  5  6  7  8  9 10

 $aa$bbb
 [1] 11 12 13 14 15 16 17 18 19 20

 $aa$ccc
 [1] 21 22 23 24 25 26 27 28 29 30

 $bb
 $bb$ddd
 [1] 1 2 3 4 5

 > a$aa
 $aaa
 [1]  1  2  3  4  5  6  7  8  9 10

 $bbb
 [1] 11 12 13 14 15 16 17 18 19 20

 $ccc
 [1] 21 22 23 24 25 26 27 28 29 30

 > a$aa$aaa
 [1]  1  2  3  4  5  6  7  8  9 10
 > a[["aa"]]
 $aaa
 [1]  1  2  3  4  5  6  7  8  9 10

 $bbb
 [1] 11 12 13 14 15 16 17 18 19 20

 $ccc
 [1] 21 22 23 24 25 26 27 28 29 30

 > a[["aa"]][["aaa"]]
 [1]  1  2  3  4  5  6  7  8  9 10
 > a["aa"]
 $aa
 $aa$aaa
 [1]  1  2  3  4  5  6  7  8  9 10

 $aa$bbb
 [1] 11 12 13 14 15 16 17 18 19 20

 $aa$ccc
 [1] 21 22 23 24 25 26 27 28 29 30

 > a["aa"]["aaa"]
 $<NA>
 NULL

Hope this helps.


TypeError: can only concatenate str (not "_io.TextIOWrapper") to str

Question: Olá, Eu estou a tentar fazer um Assisstente Virtual, mas está me a dar um erro que eu não percebo o que esta acontecendo
name = open("user_data.txt")
user = name.read()

def main():
    main_question = input("O que deseja, " + name + "?")

E dá o seguinte erro:
    main_question = input("O que deseja, " + name + "?")
TypeError: can only concatenate str (not "_io.TextIOWrapper") to str

Answer: Esse erro está ocorrendo pois você está passando a variável name que abre o arquivo para leitura. Você deveria usar a variável user pois você já fez a chamada do método .read() nela que retorna o conteúdo do arquivo.
   main_question = input("O que deseja, " + user + "?")


Como enviar variável com link no PHP

Question: então, estou com dúvidas em como fazer esse link no php:
<a href="DepoimentosPT-BR.php?id=<?php echo $_SESSION['idusuario']; ?>">Depoimentos

como vocês podem ver esse link está no html e depois é chamado o php para enviar a $ com e o ?id.
Quero saber como faço dessa maneira no php mesmo tipo:
echo "...";

Answer: Considerando $id = $_SESSION['idusuario'].

Concatenando strings:
echo 'Depoimentos';

Interpolando strings:
echo "Depoimentos";

Formatando strings com sprintf:
echo sprintf("Depoimentos", $id);

Tradução de caracteres da string:
echo strtr("Depoimentos", '{id}', $id);

Comment: Valeu meu brother, me ajudou ;;)
Comment: +1 pelo `sprintf`
Comment: @PedroLukas você deve marcar a resposta como a correta para a sua dúvida.

Como enviar variável com link no PHP


How to create OAuthClient Id in Goole API console for multiple projects

Question: I am working on an Android application, which support multiple countries like Germany, Switzerland, UK etc. For each project I have created a project in Google API console. I have generated OAuthClient Id  for my release and debug signing keys in one project.
When I am trying to generate OAuthClient Id  in another project i.e. UK, I am getting Duplicate Fingerprint error.
Is there any way to generate OAuthClient Id for same android application in multiple projects?
Answer: NO. I think its not possible. You can create multiple Oauth client id in google api console single project.
Comment: You can create or you cannot?


How do I tell Git for Windows where to find my private RSA key?

Question: My Git setup runs fine on Linux, but when I try to set things up under Windows (using Git for Windows and TortoiseGit), I don't know where to put my private SSH key (or, better still, how to tell ssh where it's located). I'm using the standard ssh.exe option during installation of Git for Windows. The setup runs fine if I allow password authentication (in lieu of RSA) on the server.
Comment: I have the same problem, I can ssh into my dev box using a public key as "root" using the "Git Bash" program that is installed with "Git For Windows" but I can't log in as "git" with my key even though I have copied my "authorized_keys" file from my "root" to my "git" user and set the owners and permissions correctly. Why can't I login as "git" when "root" works with the exact same "authorized_keys" file. Instead for "git" it passes up all the private keys, which are the exact same that work with "root" and asks for a password. This is a Centos 5.5 server by the way.
Comment: @fuzzy lollipop: Do you have the right permissions on your git user's authorized_keys file?  It should be chmod 600, and should be owned by the git user.  If it's owned by the root user, it wont work
Comment: yes all the files and directories are the correct owners and permissions
Answer: For Git Bash
If you are running msysgit (I am assuming you are) and are looking to run Git Bash (I recommend it over TortoiseGit, but I lean to the CLI more than GUI now), you need to figure out what your home directory is for Git Bash by starting it then type pwd (On Windows 7, it will be something like C:\Users\phsr I think). While you're in Git Bash, you should mkdir .ssh.
After you have the home directory, and a .ssh folder under that, you want to open PuTTYgen and open the key (.ppk file) you have previously created. Once your key is open, you want to select Conversions -> Export OpenSSH key and save it to HOME\.ssh\id_rsa. After you have the key at that location, Git Bash will recognize the key and use it.
Note: Comments indicate that this doesn't work in all cases. You may need to copy the OpenSSH key to Program Files\Git\.ssh\id_rsa (or Program Files (x86)\Git\.ssh\id_rsa).
For TortoiseGit
When using TortoiseGit, you need to set the SSH key via pacey's directions.  You need to do that for every repository you are using TortoiseGit with.
Comment: With GitBash I found I had to copy my `~/.ssh/id_rsa` file to `Program Files\Git\.ssh\id_rsa` - which was a little confusing, but now IntelliJ and Windows cmd can push to git repositories that use key authentication.
Comment: Likewise.  I just installed git-for-windows, I am running it from cmd.exe.  I needed to put the files `id_rsa` and `id_rsa.pub` into `c:\program files (x86)\Git\.ssh` . The `.ssh` dir was already present.  Thanks, JP.
Comment: Second paragraph was golden. :)
Comment: pacey's instructions for tortoisegit won't work until you have the repository (because the 'remote' configuration setting doesn't appear unless you act on a repo), and you probably can't get the repository in the first place if you can't authenticate yourself in order to clone from the origin. Tricky!
Comment: @Damon: It should be `id_rsa` without the extension. That is the file name, it is not a directory
Comment: What if I want to add [multiple keys](http://stackoverflow.com/questions/2419566/best-way-to-use-multiple-ssh-private-keys-on-one-client) which names differ from `id_rsa`?
Comment: use `ssh -v firstname.lastname@example.com` to see what files your ssh is trying to use
Comment: @DanMcClain "_you need to figure out what your home directory is for Git Bash by starting it then type `pwd`_" -- according to [Wiki](http://en.wikipedia.org/wiki/Pwd), `pwd` stands for _print working directory_ and nearly always displays _current_ (**working**) directory, not **home** one (see example in Wiki, with issuing `pwd` several times to see _different_ directory each time). As far as I'm not mistaken, **home** directory is _constant_ and does not change from time to time. To determine **home** directory in my Git Bash, I always go to it, by executing `cd ~`.
Comment: Windows 10 laziest method: type '%USERPROFILE%' in the path bar (gotten from https://git-scm.com/book/en/v1/Getting-Started-First-Time-Git-Setup)
Comment: this answer did NOT work for me. Hugh's [answer](http://serverfault.com/a/382801/97210) did.
Comment: A comment with not so many upvotes saved me, the top voted comments don't even solve anything
Comment: so I should be calling the key itself id_rsa with no extension, or putting it inside that folder?
Comment: I used "env" command in gitbash and looked for the HOMEPATH. That is where I found my .ssh folder
Comment: If msysgit detects PuTTY saved sessions it will by default use PuTTY's plink instead of ssh, so you need to set up your keys using PuTTY instead.
Comment: The latest git for windows puts an ".ssh" directory in your user directory on windows 7: "C:/Users/USERNAME/.ssh"  That is the directory that if you put an open ssh key named "id_rsa" will allow you to load the key in a git bash.
Comment: This is so helpful. Thanks for solving something that used to work perfectly and then just died
Comment: @JP. For my part, I had to put my already-generated keys to `C:\Users\xxxx\.ssh` to use them in `Git GUI 0.21.GITGUI` and `git v2.13.0.windows-1`
Comment: This accepted solution disregards the question asked, and the current addendum about moving SSH keys under `Program Files` is not viable for anyone with a multi-user machine.
Comment: @Brig `'ssh' is not recognized as an internal or external command...`
Comment: `set HOME=%USERPROFILE%` fixed the issue for me, using Windows CMD.
Comment: Also keep in mind that if you don't specify the user in the git url, git will use your Windows user name rather than the one you might have on your nix/mac machine (doh)
Comment: Finally got around to fixing this issue with msysgit/Git Bash and this answer solved it for me. Exporting the `id_rsa` file to `%USERPROFILE%\.ssh\id_rsa` worked immediately.
Comment: Adding to @trejder: you can use `echo $HOME` instead of the unreliable `pwd`
Comment: i was asked for user + password even after this explaination. I had to change the /.git/config File. Remote origin needed `firstname.lastname@example.com:...` instead of `url=https://gitlab.com...` (continue the ... according to your project, host or whatever)
Answer: Using the built-in SSH client shipped with Git for Windows, you need to set up the HOME environment variable so that the Git SSH client can find the key.
For example, on a Windows Vista installation, this would be done by issuing setx HOME c:\Users\admin\ on the command line.
It made my day and fixed the issue with Git provided that your private key is not password protected. If you want to use ssh-agent, then you can probably run ssh-agent cmd.exe (although I've never done that) and the ssh-add as usual.
Note that all Git/SSH tools are supposed to be run from a cmd.exe in order not to blink a window.
If this does not work correctly, using plink can probably be achieved by tweaking GIT_SSH. Refer to all the SVN + ssh tutorials; this is basically the same plumbing you need to setup.
Comment: This is what I was looking for since I'm trying to use the Windows command prompt, not git bash.
Comment: The `setx HOME c:\Users\admin\` command doesn't seems to be working in Git Bash. You have to use `cmd` instead.
Comment: Nice, easy fix but it would have been hard to figure out without this!
Comment: Important is as well to have no blanks between HOME = and c:\... Oct's solution did the trick for me. :-)
Comment: Worth noting - if you have spaces in your home (if you are using win XP/server 2003 you will), then you should prefix the path with a single quote. Bizarrely - if you end it with a quote that will be in the variable...
Comment: Wish I would have found this days ago. :(  Works!
Comment: You need to sign out from Windows after the variable has been updated
Answer: You can specify the key location for TortoiseGit the following way:

Open an Explorer Window.
Open the Contextmenu and navigate TortoiseGit → Settings
In the now opened window, navigate to Git → Remote
Set the path to your PuTTY key in the corresponding input box.

A screenshot is below:
Comment: Additionally if you need to convert your private key into '.ppk' format from other format you can follow [THIS](http://develop-for-fun.blogspot.com/2013/12/configure-tortoise-git.html)
Comment: Git > Remote only appears once you've successfully cloned the repository.
Comment: A much easier solution is to set everything up working properly in git (using openSSH), and then tell TortoiseGit to use the ssh.exe used by git. See http://stackoverflow.com/a/33328628/318317 That way, you only need to fix this once.
Comment: It worked for me.
Answer: None of the previous answers worked for me. Here was what worked for me in the end. It is actually fairly simple, if you know what to type. It doesn't need PuTTY.

Open a Git Bash prompt
Type 'ssh-keygen'

Accept the default location
Choose a blank passphrase
(so just press 'enter' to all questions')

Now copy the public key to your server, for example:
scp ~/.ssh/id_rsa.pub firstname.lastname@example.com:~

That's the bit on your own computer done. Now ssh into the destination server, then do
mkdir -p ~/.ssh
cd ~/.ssh
cat ../id_rsa.pub >> authorized_keys
rm ../id_rsa.pub

That's it! You're done! From Git Bash, do the following to test:
ssh firstname.lastname@example.com ls

If it lists the files in your home directory on the Git server, and then you're done!
For GitHub, you don't have shell access to their server, but you can upload the key using their website, so for the bit 'now copy to your server', do:

In Git Bash, type 'cat ~/.ssh/id_rsa.pub', select the result, and copy it to the clipboard.
On the GitHub website, go to 'Account settings', 'SSH and GPG keys', click 'New SSH key', and paste the key.
Comment: You're answering the wrong question. The Q is how to point to an existing private key.
Comment: Don't create keys without passphrases.  It's like putting your password in a text file, except that everyone knows the default location for private keys.
Comment: @GregB, I look at it like this: any server for which I create a password-less key is as secure as my laptop, it's an extension of the security perimeter of my laptop.  Actually, not even, since my home directory is encrypted ;-)  So, it's as secure as the encrypted home partition on my laptop, which is 'good enough' for securing access to github, in my opinion. (which may vary from your opinion of course!)
Comment: For the sake of the conversation, which has deviated from the original question, SSH keys are certainly more cryptographically secure than passwords, but that security is put at risk by not encrypting your SSH keys.  My personal approach is to unlock my keys at the beginning of the day using an SSH agent, which then keeps the decrypted keys in memory so that I don't need to re-enter the password throughout the day.  As @Hugh Perkins comments, and I'm paraphrasing, you all know your security requirements better than I/we do :).
Comment: @GregB Don't fall down into paranoia! :] Sure, that using password-protected keys is much more secure, than using password-less, but claiming that password-less key is as easy to break as storing passwords in a text file is an obvious false. I've seen many guides, that encourage users to use password-protected keys, but I have never seen any claiming, that using them without passwords is not secure at all. Plus: some systems doesn't support solutions for remembering key's password, entered by users, and asks for it, each time key is used. Which makes using SSH keys pointless in this situation.
Comment: Excellent answer ;)
Comment: Me too, other answers made git ask me for key passphrase.
Comment: doesn't work with github since they don't allow shell access
Comment: @GregB "SSH keys are certainly more cryptographically secure than passwords"  this is not always the case ... a 64 character password consisting of randomized characters 0-f (hex) is apparently more secure than a 4096 bit RSA key
Answer: If you're using msysgit with the OpenSSH tools, you need to either create ~/.ssh/id_rsa, or create a Git configuration in ~/.ssh/config which points to your key.
Here's an example of a Git configuration for Bitbucket that will use the correct username, and a key other than the default key (in case you maintain one key for SSH connections, and another for Git accounts).
~/.ssh/config:
Host bitbucket.org
    Hostname bitbucket.org
    User git
    IdentityFile /C/keys/yourkey.key

Once in Git Bash, you can run two commands to add your key to your current session's ssh-agent to avoid having to repeatedly type the key's password.
eval `ssh-agent`
ssh-add /C/keys/yourkey.key

Comment: I did this but for github.com:

    Host github.com
     IdentityFile ~/.ssh/github_rsa
Comment: If you have a space in your path you have to use quotes: IdentityFile "/C/My Keys/key"
Comment: My .gitconfig has sections. Under which sections should I put these hosts?
Comment: I prefer this way, because this allowed me fast connect existed keys from other PC
Answer: I just set %HOME%=%HOMEPATH%
This has the advantage of working for all users logged into the system (they each get separate .ssh folders).
In Vista:

Right-click on Computer
Choose Properties
Click on Advanced System Settings
Click on Environment Variables
In the bottom section (System Variables) Click on New
For Variable name type: HOME
For Variable path type: %HOMEPATH%
Click OK
Comment: In my case I've added HOME = %USERPROFILE%
Comment: Note that `%HOMEPATH%` does not contain the drive letter, so if your source is not on `C:` you need to prepend `C:` to `%HOME%`.
Comment: `set %HOME%=%HOMEPATH%` worked for me! Thank you!!
Comment: to cope with the fact that `%HOMEPATH%` is _not_ a full path, use: 1. via command-line, `setx HOME %HOMEDRIVE%%HOMEPATH%`; 2. via Control Panel, in step 7 above use `%HOMEDRIVE%%HOMEPATH%`.
Answer: In my case I was using Git for Windows in the Docker container windowsservercore.
My Git was installed by Chocolatey to C:\Program Files\Git.
I had to update the file C:\Program Files\Git\etc\ssh\ssh_config with this:
Host example.com
   Identityfile ~/.ssh/id_rsa

Then I was could use key from C:\Users\<user>\.ssh\id_rsa
If you are using Git for windows together with OpenSSH for Windows. Git is still using its own ssh.
Plus if you plan using ssh-keyscan host.com > known_hosts from OpenSSH, be careful because piping output from stdout of keyscan (on Windows) changes encoding to UCS-2, but OpenSSH can read only UTF-8! So make sure to change the known_hosts file encoding.
Comment: This helped, but for anyone who's using an id_dsa key, you'll also need to add "PubkeyAcceptedKeyTypes ssh-dss" under your host.
Answer: Your private key needs to be added to the SSH agent on your workstation.
How you achieve this may depend on what git client you are using, however puTTY and its associated agent (pageant) might do the trick for you, here's the link to the official binaries and source:
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
Comment: Pageant does indeed solve the problem for me -- I have a shortcut in my Start Menu's Startup folder (`C:\Users\owen.blacker\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup`) pointing to `"C:\Program Files (x86)\PuTTY\pageant.exe" "C:\Users\owen.blacker\Documents\SSH\OwenBlackerPersonal.ppk" "C:\Users\owen.blacker\Documents\SSH\OwenBlackerWork.ppk"`, so that it loads my SSH keys on startup and this makes GIT "just work"  :o)
Comment: Yeah, setup was cake on the linux side.  But I've got to have it working on Windows too unfortunately.  There are several ssh-related executable files in the git/bin folder on the Windows box (ssh, ssh-add, ssh-agent, ssh-keygen & ssh-keyscan), but I don't know how to make any of them do anything.  They just blink a cmd window open and close right away.  I'm stumped.
Comment: I stated above that I'm using Git for Windows and am using ssh.exe (packaged w/ git) in lieu of putty.  There must be some standard practice for adding a private key, I just can't seem to find out how.  While switching software may indeed allow me to log in, there has to be a way to do it with the standard Git setup, no?
Comment: Sorry i dont work on windows, only linux. But the key does have to be in your SSH agent. is there an agent.exe or something along those lines?
Comment: @OwenBlacker OMFG! You **definitely should** write this comment as a full-size **answer**! This is **the only solution here**, that actually helped me and solved my problem! Pity, that I can give you only +1! :]
Comment: @OwenBlacker I get an error 'unable to open the file' when trying to use Pageant :(
Answer: When mixing GitHub for Windows and Git GUI for Windows, you might run into issues where Git GUI keeps prompting you for a username and password. The cure for this is to change the remote URL from https: (which is what GitHub for Windows creates) to the Git protocol. In the .git directory in the configuration file, find:
[remote "origin"]
   url = https://github.com/**username**/**reponame**.git
   fetch = +refs/heads/*:refs/remotes/origin/*

Change it to:
[remote "origin"]
    url = email@example.com:**username**/**reponame**.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Comment: for SSH is the prefix always `git@{SERVER URL}` ?
Comment: Yes, as far as I've ever seen :)
Comment: Yeah it is very annoying. It is natural and easy to clone a repo with github for windows GUI, but when use git cui outside of git shell failed. I wonder how the git command in the git shell works with https url...
Comment: this is not the answer to the question
Comment: Already had this - still asks me all the time
Comment: Thank you. This saved my day.
Answer: The most efficient way is using Pageant because it will let you write the passphrase only once at the beginning of the session instead of every push. All answers here were too short, so I'll post a detailed guide here:

Download pageant.exe, puttygen.exe, putty.exe and plink.exe from PuTTY's website. Place them in C:\puttyTools directory.
Run puttygen.exe.
Click button Generate.
Wiggle the mouse around in the top part of the window until the progress bar is full, as the program asks you to do.
Provide a passphrase, and repeat it in the subsequent textbox.
Click "Save private key". The usual directory to save these in is %USERPROFILE%\.ssh (in my computer this maps to C:\Users\andres\.ssh\).
It doesn't matter what you call the key, but for demonstration purposes, I'm going to call it github.ppk. This file should have an extension of .ppk.
Copy the text in the top text box in PuTTYgen, the one labeled Public key for pasting into OpenSSH authorized_keys file and paste it into a new SSH key in GitHub's settings. Give it a title that describes what machine the key is on (e.g. "Work laptop").
Run pageant.exe, a new systray icon will appear.
Right click on the icon -> Add key.
Locate your ppk file, enter your passphrase.
Create these new user environment variables (via looking for application Environ through WindowsMenu which will find Edit environment variables for your account): GIT_SSH = "C:\puttyTools\plink.exe" and SVN_SSH = "C:\puttyTools\PuTTY\plink.exe"
Open putty.exe and try to connect to the host where you host your Git repositories. For example, try to connect to github.com via SSH, and a dialog will ask you if you accept the fingerprint of the server: click on YES.
Run a new instance of your MINGW64 Git console, and verify that the environment variables are there by writing the command env | grep -i ssh.
You should be all set. Try to clone with the Git + SSH protocol from your host.

(Originally extracted from these two guides which I combined in one: How to setup Git for Windows and Configure MinGW-W64+MSYS to use PuTTY Plink/Pageant.)
Answer: I had similar issues and none of the answers here solved the problem. It turns out, my key pair were originally generated with an empty passphrase. (I know, dumb.)
Once I created a new keypair and uploaded the public key to GitHub, things started working again.
Comment: this.  ughhhhhhhhhhhhh. good bye 2 hours
Answer: The standard location for the files is in %USERPROFILE%\.ssh.
%USERPROFILE% is the equivalent of $HOME in Unix (normally maps to something like c:\users\youruserid).
If you are using the SSH tools that came with Git, which are the standard command line Unix-style tools, you can use something like my script here to work with ssh-agent across all shells.
Comment: (sorry, StackExchange character limits on comments).  Here is more details about the folders and a brief description of what goes in each.  There are other resources as well, including more consumable blog posts, but this one offers the most technical accuracy: https://technet.microsoft.com/en-us/library/cc749104(v=ws.10).aspx
Comment: For future readers, `%USERPROFILE% is the equivalent of $HOME` is _not_ the equivalent of `$HOME`.  A lot of bad acting Linux apps ported to Windows treat t the two the same e but they should _not_ be treated the same.
Comment: Micah, can you inform the differences in intent for that?  Also, even with different intent, it would seem that if all the tools use one as the other, then doesn't it effectively become equivalent?
Comment: Tools that use `%USERPROFILE%` on Windows in the same way as `$HOME` on Linux are violating well documented best practices/recommendations for Windows development (published by MS long ago and updated over time).  There are many tools that do this, but the argument to follow them is much like the argument "X pees in the pool, so we should too."  `USERPROFILE` is where the user stores documents _they_ create/save (e.g., save dialog).  `APPDATA` is for per-user configuration data.  `LOCALAPPDATA` is for per-user caches and large files.  `PROGRAMDATA` is for machine-wide configuration and cache.
Comment: In general, the only tools that misbehave with USERPROFILE are tools written by Linux developers and then ported to Windows.  As a developer, you probably use a lot of these so it _feels_ like "everyone is doing it" but outside of the development tooling ecosystem most Windows applications actually are good citizens.  Even Microsoft sometimes makes the mistake of not putting things in the right place (they are a huge company), though in general when you point it out to them they make an effort to resolve the problem and follow OS guidelines.
Answer: I've fixed the above issue by creating

~/.ssh/config

file and put:
IdentityFile C:\Users\adria\.ssh\mysshkey

Comment: OH MY GOD THIS WORKED FOR ME WHEN NO PREVIOUS ANSWERS WORKED!
Answer: OK, I looked at the suggestion of ..
But placing in my private SSH keys in public folder I didn't think was a good idea, so I started to look for where the knownhost was.
So if you want to correctly protect your SSH key you need to put your key in the following directory:
For Windows 7, 8, and 8.1 32-bit:

C:\Users\\AppData\Local\VirtualStore\Program Files\Git\

For Windows 7, 8, and 8.1 64-bit:

C:\Users\\AppData\Local\VirtualStore\Program Files (x86)\Git\
Comment: This was the simplest solution on my Win7 machine.  Like you, I searched for `known_hosts`.  Sure enough, it was in `C:\Users\Dave\AppData\Local\VirtualStore\Program Files (x86)\Git\.ssh`.  By placing my key file (id_rsa) in that directory, ssh was able to find it without complaint.  I did a little reading - this is how Windows handles (legacy) software attempting to write to forbidden areas (such as "C:\Program Files\"), so Git's ssh is completely unaware that it is writing to the VirtualStore directory, Windows is handling that transparently.  At least these files belong to a user!
Answer: You can specify both the path to the key and the name of the key file like so (on Ubuntu). For example:
ssh -i /home/joe/.ssh/eui_rsa

Comment: This absolutely solves the problem and allows you to store your keys where ever you would like.
Comment: The question was specifically about windows. I have git on my Ubuntu machine working like this, but I can't tell what to set `GIT_SSH_COMMAND` to on my Windows machine.
Answer: The following answer also applies to this question when running ssh from Windows Service Account: Jenkins (Windows Service) with Git over SSH
Comment: Following the link you provided I was able to get my Jenkins setup.  I needed to set the HOME environment variable to the Git program path which held the .ssh directory I created my SSH key in.
Answer: Pageant (an SSH agent supplied with the PuTTY bundle) solves the problem for me.
I have a shortcut in my Start Menu's Startup folder (C:\Users\owen.blacker\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup) pointing to "C:\Program Files (x86)\PuTTY\pageant.exe" "C:\Users\owen.blacker\Documents\SSH\OwenBlackerPersonal.ppk" "C:\Users\owen.blacker\Documents\SSH\OwenBlackerWork.ppk", so that it loads my SSH keys on startup and this makes Git "just work" :o)
Comment: I think you need several other settings correct for this to work (such as GIT_SSH set to TortoisePLink.exe I think?), and although it has worked for me in the past, I often get problems with it on other machines. :-(
Comment: I get 'Unable to open the file' from Pageant :( Which I know is set up correctly as I'm using it for TortoiseGit :(
Answer: My msysgit OpenSSL/Bash Git experience (not PuTTY's plink) is that the search order for your the .ssh/ folder is as follows.

%HOME%/.ssh/
%HOMEDRIVE%%HOMEPATH%/.ssh/
%USERPROFILE%/.ssh/

Hence why so many people suggest setting HOME if one of the others is not what you expect. More importantly, you can check for yourself; to debug use ssh -v to a server that uses public key authentication as follows:
$ ssh -v email@example.com
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Reading configuration data /d/.ssh/config
...
debug1: identity file /d/.ssh/identity type -1
debug1: identity file /d/.ssh/id_rsa type 1
debug1: identity file /d/.ssh/id_dsa type -1
...
debug1: Next authentication method: publickey
debug1: Trying private key: /d/.ssh/identity
debug1: Offering public key: /d/.ssh/id_rsa
..
Hi kcd83! You've successfully authenticated, but GitHub does not provide shell access.

We found ssh searching on an obscure drive and none of the previous answers seemed to explain what we saw.
Sometimes %HOMEDRIVE%%HOMEPATH% is a mapped network drive (e.g. H:/) which causes unnecessary failures when there are network/fileserver issues, even when %USERPROFILE%/.ssh is C:/Users/Username/.ssh and has the keys locally. Setting %HOME% to %USERPROFILE% stops it looking at the remote home drive.
Comment: this answer helped me solve a very peculiar issue where the encryption algorithm of my key wasn't supported by one of the operating systems I was using
Answer: TortoiseGit lets you specify the key to use when cloning a repository. Simply check "Load Putty Key" and browse to the .ppk file, as in the screenshot:
Comment: If disabled, check `Settings... -> Network -> SSH client` is set to `C:\Program Files\TortoiseGit\bin\TortoiseGitPlink.exe`
Answer: Using Windows 10, I could not get the pageant generated SSH key working (at least for Git on the command line, using SourceTree I didn't have an issue) when running:
git push origin master

So my solution:

I opened 'Git Bash'
Ran
ssh-keygen

Confirmed keys now exist
ls ~/.ssh

Opened id_rsa.pub in Notepad++, selected all the contents
Added a new key in Bitbucket, https://bitbucket.org/account/user/myusername/ssh-keys/
Labelled and pasted contents into the key field --> Add Key

After that, command line Git worked. It appears that it wants the old PEM format, because if I try to import this key into pageant it says as much.
Answer: Many answers say this, but for me not fast enough!
in windows using msys (standard windows console) C:\Users\{you}\.ssh\id_rsa
Basically it doesn't bother scanning installed keys (at least not on my new laptop) and so needs specifically id_rsa
I encountered this wanting to clone some private work repo's in ruby MSYS CLI for windows 10 64-bit
Answer: Reading your comment to Declan's answer, try opening a command prompt first (Start → Run → cmd) and then navigate to that git/bin folder and run ssh-keygen. Theoretically that will generate an RSA key and place it in the appropriate directory. Then you just have got to find it and share your public key with the world.
The reason that the window "blinks" is because Windows runs the program, and when it executes, it closes the command prompt, thinking you're done with it, when you really need the output.
Answer: Using v0.17 of Git Gui on Windows I clicked on the following menu command:
Help → Show SSH Key.
A dialog appeared entitled Your OpenSSH Public Key. I generated a key and copied it to the clipboard. Then I continued to follow the setup-ssh instructions on githelp from Step Three onwards. Afterwards Git Gui communicated with GitHub silently - no need to enter any credentials.
Answer: On my Windows 7 system Git Gui looks for the RSA key in the userprofile/.ssh folder or more specifically c:/users/yourusername/.ssh/.
The tricky part for my setup was getting the shared host at hostmonster to accept the key. The only way I could get it to work was by using Git Gui to create the key pairs (without a password) and then copy and pasting the public key via the control panel, ssh, manage keys.
To start at the beginning, you have to create the keys in Git Gui by going to menu Help, Show SSH key, then Generate Key. Now you will have two new keys in the .ssh directory. Open the .pub file and copy the contents.
Log in to your control panel on the shared host and go into SSH, Manage SSH keys, and Import key. Paste into the Public box, and make sure you name it the right name without the extension-- mine was id_rsa. Now you must authorize the key using the manage authorization link, so it will get concatenated into the authorized_keys file.
Now your Git Gui and your Git Bash should be able to push using SSH without having to type the password. Oddly, I was able to push using SSH via Git Bash and Git Gui just fine on my own servers running Linux, it was just the shared hosting that was giving me fits. I hope this helps someone as it took me hours of trial and error to come up with this--and it's so simple!
Answer: If you're on Windows 7/8, you should look in C:\Users\Your_User_Name.ssh
Just copy & paste your id_rsa file here and it will all work out-of-the-box.
Answer: If you are using the Git command line for Windows you can do as follows:
Open cmd.exe and execute setx HOME c:\PATH_TO_PRIVATE_KEY.
Create a new folder, .ssh, (if not exist) inside c:\PATH_TO_PRIVATE_KEY and copy your id_rsa file (your private key) into it.
Done. Now you can use the Git command line normally.
Answer: One mistake I made when using SSH on Windows was that when I attempted to use the keys through the Git Bash client, all of the files within ~/.ssh were the wrong permissions, yet it did not attempt to tell me that it was a problem.
Just as a test, make sure you've set everything in your ~/.ssh directory to chmod 600.
Answer: If you have the necessary permissions on the Windows machine, and your policies permit it, I would suggest installing Cygwin (https://cygwin.com/), especially considering that you have prior experience with Linux. Cygwin will make it possible to handle your ssh-keys as you would on any other Linux/Unix machine. And it provides access to almost all of the cli tools of Linux.
Comment: It is perfectly reasonable to make suggestions like this as comments. But as the question explicitly requests git for windows you should expect down votes for posting this as an answer.
Answer: You can also load PuTTY Agent (pageant) and add the private key you generated with PuTTY for the server.
Git recognizes this and uses that for push/pull.
Answer: I was using TortoiseGit as well as Git Bash on Windows, depending on need. I've added everything into TortoiseGit, and it worked fine, but Git Bash wasn't picking it up even though the keys were in the correct directory. It turns out I had to do this from Git Bash:
ssh-add C:\\Users\\<YOUR_USER>\\.ssh\\id_rsa

You can of course change the path to wherever your key is located, remembering to use \\ as the separator.
Answer: If using Git for Windows, once the SSH keys have been generated, you must add your SSH key to ssh-agent.
See Generating a new SSH key and adding it to the ssh-agent.
eval $(ssh-agent -s)

// Tell where the keys are located

ssh-add ~/.ssh/id_rsa

Comment: the widely accepted answer did not work for me whereas this one did. I believe it might help someone to know the key must be added to the ssh agent and it can be done with 2lines of instructions
Comment: Welcome to Server Fault.  This question already has a widely accepted answer accepted several years ago.  Keep looking for newer questions or those that can be significantly improved.
Answer: Windows --> Preferences --> ssh2--> general--> load the private key .
The pair's public key should have been uploaded to the git and voila things should work.
Answer: This is not an answer, but it might still help some who who find this question only since they think they need a key pair authentication and oversee that there is another way as well:
I could clone from Gitlab with Tortoise with the https link instead of the ssh link. Yet, this worked only after a first login in Gitlab on that same terminal server. I had forgotten to log in on that machine since I was already logged in on my home computer. When I started working on a terminal server, I did not log in at first.
Do this only if you are in a safe network. Else, take ssh with its end-to-end encryption.


F-chord on Ukulele (hand position)

Question: I'm a ukulele beginner and I'm finding it almost impossible to play the F-chord without my finger accidentally touching the A or the C strings. I have looked through YouTube but no matter what, I can't seem to find a position where I can hold the F and have all four strings play cleanly.
I can play the G string with my middle finger cleanly. I can also play the E string with my index finger cleanly. However, it seems that when I put them together, it doesn't work.
It might be just a matter of practice but it's been a week now and other chords like the G-chord were a lot faster to learn even though they're supposed to be harder. I think I'm doing something wrong with my hand. Any tips on how to hold my hand?
Comment: Have you tried using other fingers? For example using the index and the ring finger?
Comment: @infinitezero interesting, I will try this.
Answer: You could try a different voicing. Instead of 2-0-1-0, try 5-5-5-3 (with fingers 2,3,4,1) or 5-5-5-8 (fingers 1-1-1-4, using a barre).
F is probably one of the trickiest of the basic chords to play cleanly as a beginner, very much like C on the guitar. Keep trying and you should eventually get it, but an alternate voicing might help you to get through the song you're learning and stay motivated.
Another thing to try is different placement of the thumb on the back of the neck. If the neck is sitting in the pocket of your hand, the fingers have to curl more to fret the strings and that curling could make it more difficult to fret one string and not touch the nearby ones. Try putting the thumb in the middle of the neck so the fingers and thumb are kind of "pinching" the neck and string between them. This makes the fingers a little straighter and it may be easier to control. Using a strap would help with this so you don't have to support the instrument with the same hand.
Answer: I am wondering if you might need a bigger instrument.  Have you ever tried playing on a tenor?  Of course I don't know what size you are using at the moment.
Comment: To tell you the truth, I don't either. This was a Ukulele bought second hand for ten bucks and it's my first musical instrument. I'm average sized though and don't think I have fat fingers - my first suspicion is to blame my technique, not the instrument.

F-chord on Ukulele (hand position)


Writing sequences in the language of arithmetic

Question: I am trying to write a theorem of arithmetic purely in the language of arithmetic. As a simple example, consider the theorem
$$\forall m \quad 2(1+\cdots+m) = m(m+1)$$
This is a well known theorem of arithmetic, but the above statement is imprecise. It requires you to interpret the '$\cdots$'. How can this statement be formalized?
I emphasize that I would like to state this purely in the language of arithmetic,
ie. using only the symbols $0,=,+,\cdot,<$ and regular first order logic symbols.
Answer: The standard way to formalize a "$\cdots$" in the first-order language of arithmetic involves using a recursive definition to give meaning to the ellipsis, and then expressing the recursively defined function using Gödel's $\beta$ trick.
That is, however, fairly tedious if you want to write it out completely.
In your particular case, you can reasonably hope to get away with claiming directly that the function $f(m)=m(m+1)$ satisfies the recursion equations
$$ \begin{align} f(1) &= 2 \\ f(m+1) &= f(m)+2(m+1) \end{align} $$
Comment: For the general case I think you ought to find and work through a presentation of Gödel's incompleteness theorem, which should to include a development of how to represent recursion in first-order arithmetic. As a concrete recommendation, Peter Smith's [Gödel Without (Too Many) Tears](http://www.logicmatters.net/igt/godel-without-tears/) is free and pretty good.
Comment: @Owen: The example here does not actually depend on introducing a new function symbol -- you can view my $f$ as a meta-level abbreviation because the function is defined directly by an expression. The second of my equations then becomes $$(m+1)((m+1)+1)=m(m+1)+2(m+1)$$
Comment: I am not interested in this particular case. I'm actually interested in seeing Goodstein's theorem precisely stated.
For the current example, can you do it without first defining some function recursively? I want to avoid introducing a function symbol, which is not in the language of arithmetic. The only function symbols at our disposal are $+,\cdot$.


NFL record for most number of interceptions within one instance of scoring?

Question: My brother and I were discussing some things when a question of curiosity came up that Google could not seem to answer:
In the NFL, what is the record for number of interceptions (by either team) within one instance of scoring (either touchdown or field goal)?
To be clear, we're curious as to the greatest number of interceptions that occurred before either team in an NFL game managed to score any points. Note that this could happen before the first score of the game or between two instances of scoring. For example if team A scored a touchdown, and went on to intercept team B, and then be intercepted before team B scored themselves.
I'm guessing it's probably 2 or 3 interceptions before someone scored, but who knows?
Answer: So the best odds to find this statistic is to look at the games that ended in a 0-0 tie or went into the 4th quarter without scoring. This way you know that the either team hasn't scored for a good majority of the game, meaning that the odds are much better that there have bee numerous interceptions before the first score.
There have been 73 games that have ended in a 0-0 tie, and the last one to happen was in 1943 with the New York Giants and the Detroit Lions. I observed a list of all NFL games that ended in a tie game, but the team stats for those games are only held back until 1935. There were two games that had 7 interceptions in them, but the game still ended in a tie. October 1 1939, Washington Redskins vs. New York Giants and the other was the Detroit Lions vs. Chicago Cardinals on September 15, 1940. The way the NFL's offense used to be run is not as dominant as it is now. Tie games in the 40s were very prevalent. But, once the formation of the offensive line changed then the tie games became very scarce.
I also researched games that games that went late into the game before scoring. November 27 2007, the Steelers beat the Dolphins 3-0 by a field goal with 17 seconds left. Although, there was only one interception in this game. The low scoring games I looked at didn't nearly have 7 interceptions, but that game went scoreless.
This link  below (I'm not sure if you already looked this website up) is a vey good site for finding NFL statistics. It has statistics dating back to the 1920's.
http://www.pro-football-reference.com/


Efficiently Calculate Accuracy of NN

Question: The current way I'm calculating accuracy is very inefficient. This is because I'm looking at the entire dataset together whereas in my forward propagation I broke it down into batches.
How would I test accuracy efficiently in a separate function? One way is to break up the test data into batches and run the model on each batch, then concatenate all batches and test against the true labels. Is there a quicker way? Also is the way I'm using the model to make predictions on a different dataset the most efficient way to do so or should I be also breaking that down into batches?
Ideally, I would like to have this separately in a method so that I can call accuracy for train, test and dev datasets.
This is the part of my code that is running the model:
cost = compute_cost(fc_layer_4, yph)
optimiser = tf.train.AdamOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    mini_batches = random_batches(X,Y)
    num_batches = len(mini_batches)

    for epoch in range(num_epochs):
        epoch_cost = 0
        for batch, (x_mini, y_mini) in enumerate(mini_batches,1):
            _,c = sess.run([optimiser, cost], feed_dict={xph:x_mini, yph:y_mini})
            epoch_cost += c/num_batches
            print("epoch: ",epoch+1," / ", num_epochs,"... batch: ", batch)

        costs.append(epoch_cost)

    plt.plot(costs)

    W1,b1,W2,b2 = sess.run([W1,b1,W2,b2])

return W1,b1,W2,b2

I would then like to store the prediction to return it later and use it to calculate the accuracy. I would also then use a method similar to the following to make predictions on different datasets:
def predict(X,parameters):
    W1,b1,W2,b2 = parameters
    conv_1 = convolution(X,W1)
    activation_1= tf.nn.relu(conv_1)
    pool_1 = max_pooling_2_x_2(activation_1)

    conv_2 = convolution(pool_1,W2)
    activation_2 = tf.nn.relu(conv_2)
    pool_2 = max_pooling_2_x_2(activation_2)

    flattened_3 = flatten_layer(pool_2)
    flattened_3 = tf.nn.relu(flattened_3)

    fc_layer_3 = fully_connected_layer(flattened_3,1024)
    fc_layer_4 = fully_connected_layer(fc_layer_3,10)

    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        prediction = sess.run(fc_layer_4, feed_dict={xph:X})

    return prediction

Comment: Usually you create batches as large as fits the GPU memory. From the efficiency point of view it does not make any difference if you pass them through one by one or all at once.
Comment: You can also write an algorithm to extract at random a (smaller) subset, which you can use for performance assessment.
Comment: Why do you think evaluating accuracy per batch is more efficient than evaluating it on all samples at once?
Comment: My computer is old and crashes if I run it on all samples at once. Any ideas on writing a separate function for accuracy?
Comment: Also, what if I have hundreds of thousands of records in a test set. What is the conventional way of testing for accuracy?
Answer: For future reference:
After taking the comments into consideration, I got it sorted out. My answer is the content of another question I've asked which can be found here:

Efficiently Calculate Accuracy of NN


Second derivative of $\sec(3x)\sqrt{324\cos^2(3x) + 396 + 121\sec^2(3x)}$

Question: How to take second derivative of $$\sec(3x)\sqrt{324\cos^2(3x) + 396 + 121\sec^2(3x)}.$$
I am having trouble with taking the second derivative of this. I know I should simplify it before taking the derivative but I'm not sure how to do that.
The final part is I have to find the second derivative at $\pi/12$ , but my main question is how I would simplify $$\sec(3x)\sqrt{324\cos^2(3x) + 396 + 121\sec^2(3x)}$$ before taking the derivative.
$0 < x < \frac{\pi}{6}$
Comment: Have you tried anything yourself?
Answer: Notice that if we set $$u = \sec 3x,$$ then the quantity in the radical is
$$\frac{324}{u^2} + 396 + 121 u^2,$$ which turns out to be a perfect square of a rational expression---can you see how to find it??


Pentaho: How to read SQL result row by row to execute one by one?

Question: i built a simple transform for select rows data from table in the database using Table Input.
i know that Table Input return all result one time. but what i need to do is to get result row by row and continue the process, then return back to the next row and so on.
so any ideas please ?
Answer: Answer from Pentaho Forums :

Build a job, and let the first transformation retrieve all the rows
  via Table Input. Use a "Copy rows to result" step to save the result.
  Create a second transformation configured for single row execution -
  see advanced transformation settings. Use "Get rows from result" to
  start single row processing.

in addition to :
Transformation Executor


WebDAV drive map error 67 on Windows Server clients (not Win 7/10)

Question: I have an IIS server that I've configured WebDAV on so a certain directory can be drive mapped on remote clients.  Almost of the client computers that will need to use this are Windows Servers versions from 2008 R2 through to 2016.
On my Windows 10 PC, I can drive map the WebDAV URL without issue.  I'm on the LAN.  I can also map it on my home PC fine - it is also Windows 10, but on an entirely different network.  Also connects OK on Windows 7 systems on the LAN and elsewhere on the internet.
The command I'm using is net use p: http://pe-distribution.corporatedomain.com.au /User:pe.user P@ssw0rd /Persist:YES and the P: drive appears straight away and I can read/write without issue.

But if I try to run the same on any of the client servers (Windows Server Std 2008 R2/2012/2012 R2/2016) that will need to use it, I receive the very unhelpful

System error 67 has occurred. The network name cannot be found.

I've even tested other Windows Servers on the same LAN as the ISS server and they fail.
Is there any security policy or registry settings in the Windows Server OS that need to be modified for NET USE to work with http/https?
Or something else I've missed in the IIS config?
Answer: OK, I don't know if this is a proper solution or not, but it seems to have worked.
On each of the Windows Server 2008 R2, 2012 and 2012 R2 systems I installed the "Desktop Experience" feature and was able to map the drive.
For the Windows Server 2016 system - which was installed as "Desktop Experience" (as opposed to the core install) - I had to add the "WebDAV Redirector" feature.
So obviously Win 7/8.1/10 have the WebDAV redirector (WebClient) baked in, but the server OS needs the feature to be added.
I find it strange that it is required at all for a WebDAV client.
Anyhow, because of the inconsistencies with the Windows WebDAV client, I've added an extra step in my drive mapping batch file.  Some of the systems didn't map the drive on the first attempt, but did on the second.  So by using the authentication without mapping a drive letter, it initiates the connection so the drive map then worked without fail.
The batch file is scheduled to run each day at 6am and on system restart in order to keep the drive available.
@echo off
net use P: /DELETE /Y
net use pe-distribution.corporatedomain.com.au /User:pe.user P@ssw0rd /PERSIST:Yes
TIMEOUT /T 3
net use P: pe-distribution.corporatedomain.com.au /User:pe.user P@ssw0rd /PERSIST:Yes


Finding of roots for the given equation

Question: The equation $$|\ln (mx)|=px$$ Where m is a positive constant has exactly two roots for
$(A) p=\frac{m} {e} $
$(B) p=\frac{e} {m} $
$(C) \frac{e} {m} \geqslant p >0$
$(D) \frac{m} {e} \geqslant p>0$
My attempt:
Drew the graph for $|\ln(mx)|$ and then found that for a single root $y=px$ would have $p>\frac{m} {e} $
 And hence,  if $p$ is less than that value, then $y=px$ would have two roots until $p$ becomes less than$ \frac{m} {e}$ . So $p$ has only one value for two roots and that is $\frac {m} {e}$.  Is my attempt correct?
Comment: Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: We have that
$$f(x)=|\ln (mx)|$$
has a minimum at $mx=1$ that is $f(1/m)=0$ then to intercept $f(x)$ we need that $p\ge 0$.
For $p=0$ we have only one solution, then assume $p>0$.
For $x<\frac1m$ the line $y=px$ always intercepts $f(x)$ at one point.
For $x>\frac1m$, in order to have exactly one intersection point, we need that $y=px$ is tangent to $f(x)$  that is
$$f'(x)=\frac m {mx}=p \implies x=\frac 1p \implies y=1 \implies mx=e \quad x=\frac e m\implies p=\frac m e$$
therefore to have exactly $2$ solution we need
$$p=\frac m e$$
Comment: Sorry but it is not the correct answer. Correct option is (A). Also you have just considered the case where $x>\frac{1}{m}$.
Comment: @jayant98 Ok I revise that! Thanks
Comment: @jayant98 Yes of course, the line y=px always intercepts f(x) for x<1/m and to intercept at one point f(x) for x>1/m we need tha f(x) and px are tangent that is p=m/e.
Comment: Yes. That's what I had given in my attempt. So,  now, I think my solution is correct. :))
Comment: @jayant98 Yes and we can obtain that by the tangency condition.

Finding of roots for the given equation


Question on isosceles triangle

Question: Let $ABC$ be a triangle such that there exists $N \in [AM]$ such that the angles $BAN$ and $CAN$ have the same measure, where $M$ is the midpoint of the segment $BC$. Then $ABC$ is isosceles. One hint?
Comment: It is spelt: isosceles. You can google it and it will give the correct spelling, so there is not excuse.
Answer: The angles $BAN,CAN$ are the same as angles $BAM, CAM$ respectively. That is, they are the angles that the angle bisector make with the two other sides. There is a theorem saying that the bisector cuts the third side in the same ratio as that of the two sides going to the ends of the third side. So if $M$ is the midpoint that ratio is $1,$ and ...
Edit: The use of the above mentioned theorem can be avoided by using the law of sines. At one point one needs that $\sin(\pi-x)=\sin(x).$

Question on isosceles triangle


limit of $\frac{x^x -1}{x}$ as x tends to zero

Question: I was wondering if i could get any help with the following:
$$ \lim_{x \rightarrow 0^{+}} \frac{x^x -1}{x} $$.
thank you.
My attempt:
$$ \lim = \frac{e^{x \ln(x)} - 1}{x} = \lim ( x \ln (x)( x \ln(x) + 1)) $$
Comment: Your $\frac{x\ln x-1}{x}$ should have been $\frac{e^{x\ln x}-1}{x}$.  And your differentiation of $x\ln x$ was not correct.
Comment: @AndréNicolas thank you
Comment: You are welcome.  The basic L'Hospital's Rule strategy was fine.
Answer: Use L'Hopital's rule to get:
$$\lim_{x \to 0} x^x(\ln x+1)=\lim_{x \to 0}x^x \ln x-\lim_{x \to 0} x^x=(\lim_{x \to 0} x^x \ln x) -1=((\lim_{x \to 0} x^x)(\lim_{x \to 0} \ln x))-1=(1)(-\infty)-1=-\infty$$
The limit does not exist.
Comment: @AhmedS.Attaalla Not necessarily.
Comment: @AhmedS.Attaalla  http://math.stackexchange.com/questions/127689/why-does-a-limit-at-infinity-not-exist and http://math.stackexchange.com/questions/3203/infinite-limits
Comment: Why does it not exist? How would you show one side goes to something else.
Comment: @AhmedS.Attaalla Because $-\infty$ wouldn't be a limit per se.
Comment: I thought DNE was only used to show that the RH limit does not agree with the LH limit.
Answer: We may also avoid De L'Hospital theorem. Since
$$ \lim_{t\to 0}\frac{e^t-1}{t}=1\quad\text{and}\quad \lim_{x\to 0^+} x\log(x)=0,$$
we have:
$$ \lim_{x\to 0^+}\frac{x^x-1}{x}=\lim_{x\to 0^+}\frac{e^{x\log x}-1}{x\log x}\cdot\log(x) = \lim_{x\to 0^+}\log(x) = -\infty.$$
Comment: Nice. Does it make a difference to use ln or log in this case?
Comment: @gnp: no, it doesn't. For my standards, $\log$ means the natural logarithm as well as $\ln$.
Answer: Use an asymptotic expansion:
$x^x=\mathrm e^{x\ln x}=1+x\ln x+o(x\ln x)$, hence
$$\frac{x^x-1}x=\frac{x\ln x+o(x\ln x)}x=\ln x+o(\ln x)\sim\ln x\xrightarrow[x\to 0^+]{}-\infty.$$


nivo slider not working properly

Question: I am new user of Drupal 7.3 also using View Nivo Slider in our project but nivo slider not working properly.
When I am traying to uploading images in nivo slider, uploading time is too much. I think images is not uploading. Please give me solution and in status report I am getting error message i.e.

"Error    Nivo Slider jQuery version  jQuery 1.4.4 .Nivo Slider requires
  jQuery 1.7 or greater. Configure jQuery Update."
Answer: What the error is telling you is that you need to download and install Jquery Update module.
Then you need to configure jquery update in

/admin/config/development/jquery_update

and change the default version to grater than 1.7
Comment: @sachinGaikwad `clear cache` and check again because the error message clearly says it's jquery version issue. and do check your `Nivo slider` library version. also don't forget to read `README.txt` it contains all the documentations you need to follow to make it work. cheers.
Comment: no its not working.i installing this module and change version but its not working.in the status report the same error message will be occurd

nivo slider not working properly


LINQ's OrderBy behaves different in Visual Studio's Immediate window than within the code

Question: i see diffrent results when using LINQ's OrderBy function on a list in .NET and Visual Studio's Immediate window:
Info

Visual Studio 2022 Enterprise 17.4.4
.NET 6 Console project

Code
var l = new List<string>() {
            "a-test.de",
            "a.de"
        };

Console.WriteLine(l.OrderBy(e => e).ToList().First());

Result when running the programm
Output is "a-test.de"
Result when using the immediate window
If i set a debugger after the console output and i run l.OrderBy(e => e).ToList().First() within the immediate window the output is "a.de"

The question
What am i missing? :)
Thank you very much
Comment: @wenbingeng-MSFT i don't now exactly what you asking for - the question is asked in the initial post :)
Comment: This is normal, as this is a feature that even windows itself comes with. Please refer to https://learn.microsoft.com/en-us/visualstudio/ide/reference/immediate-window?view=vs-2022
Answer: I suppose it depends on your current culture
Try to specify comparer for OrderBy
 var l = new List<string>() {
            "a-test.de",
            "a.de"
        };

Console.WriteLine(l.OrderBy(e => e, StringComparer.Ordinal).ToList().First());

It should achieve the same behavior
Comment: Well, it does solve the issue, but doesn't explain. The culture should be the same between  execution and evalution at immediate window, the context should be the same. It's strange that they produce different results
Comment: Interestingly, the result of the immediate window behaves the same as in a Powershell instance `@("a-test.de", "a.de") | sort | select -first 1` returns also `"a.de"`


Avoiding Bias Through Model Selection

Question: I have a application where a logistic regression model is used to make a decision. Each time a user enters the application the model is fed inputs, and it outputs some decision. The first model was trained on data obtained by selecting a decision at random and displaying it to the user. The resulting model performs better than random and has been running online for a while now.
The data of each impression (when a model is given the chance to make a decision) is logged and used for training and comparison of future models
My concern is that future models will be biased because they are being trained on data generated from my current model. Is this concern true? And how can I avoid biasing future models?
One thought: Since the current model is running on 100% of traffic, I could sacrifice maybe 5% to be a random decision. This would allow me to collect unbiased data which I could use to compare models in an unbiased manner. One problem with this approach is that 5% of my data is probably too small a sample to train or test on.
Toy Example with CTR prediction:
Lets say app displays a photo to the user. For each opportunity to show a photo, there are several(could be 1000+) photos which the model must select from to show to the user. Each opportunity may have a different set of photos to select from depending on factors. Whether the user clicks on the photo which the model chose is logged and this data is what i plan on using to train models in the future. The LR model is 5-fold cross validated on 70% of the data, and 30% is left for testing.
The problem i am describing here appears to be an inherent problem with models who's prediction is used to make decisions which affect the data that a later iteration of a model would be trained on.
Note: The LR model produces a ranking for all photos which can be shown. then the best ranked is shown.Scores for photos are recomputed every X many days.
Comment: Im still confused how anyone is supposed to setup a pipeline correctly to avoid bias when the model your using influences the data thats being collected. Am I using an LR model in an incorrect way? should LR models not be used to make in-the-loop decisions?
Answer: The answer regarding bias is YES, using your model for in-the-loop decision support influences the outcome.  Data modeling almost invariably starts from the treatment of observations as a dependent variable, with independent variables that interact in an unknown system to produce the observed results.  Modeling approaches attempt to infer or estimate from observation the hidden workings of the generating system (with wide variations in approaches and assumptions).  In this case, your existing LR model is part of the generating system (since it leads to decisions that influence outcomes), so any attempt to model this system by other means will reflect its ability to predict, in part, how your existing LR model impacts observed outcomes.
Your application is almost more in the domain of control theory rather than pure data modeling, since you are using a combination of a predictive model and a control signal to shape outcomes.  "Pure" data modeling attempts to predict outcomes from input values, while your application attempts to dictate them based on probabilistic predictors.
This is the case for many real-world problems though.  In such cases, the real objective is not to get the best predictor of outcomes, but rather to optimize the expected outcomes of decisions that are conditioned upon a predictive model of the response to specific inputs (which now include decision variables that are in the system's control).  This plays into stochastic optimization and decision theory, which live outside the domain of strict data modeling.
Comment: Im not sure i understand why my example would fall under control theory and exactly how anyone could use a "pure" data model. I would think that most models which are being trained to predict the outcome of an event are intended to be used for in-the-loop decisions. Could you give an example of how stochastic optimization and decision theory are used to make in-the-loop decisions.
Answer: Bias is perhaps not the right term. The model estimated effects are "true" in the sense that they are internally valid, or that they "generalize" only to those data which you've collected (not any kind of generalization at all). The more pertinent issue is that they may not generalize to external data which would be collected in a follow up or independent cluster. Those independent data would give rise to a different model, but the difference between those models would not be bias, but just difference between two internally valid models with no external validity. A fitting method which estimates the same effects in both independent datasets could be said to be externally valid. Otherwise the method is flawed.
The truth is your model is overfitted. This leads to biased effect estimates, but the bias is not the issue. The fact is that this model is not guaranteed to generalize to future or separate data collection, it is not externally valid.
This is a bigger issue than just cross validation, its an issue of defining the scope of your model. Nonetheless, cross validation will help relieve the bias, partially by encouraging you to fit a model on a smaller fraction of the total training set. A better approach yet is to focus on the science of the problem and what is known about the larger temporal and spatial frame whence these data came.
Comment: I am already cross validating and it has not helped
Comment: @lufthansa747 I don't think you've described your methods properly. Basically even with cv you would ideally reserve an independent segment of your data to validate your model. That's internal validation. Without any external validation, how do you know your model is wrong?
Comment: i have done both online and offline evaluation of a identical model to my current one, except trained on newer data and the model did substantially worse. Im using MXE and NDGC as metrics to compare models.
Comment: @lufthansa747 It's a given that predictive models will perform worse. To expect consistent performance between data collection efforts is absolutely crazy. You should be defining metrics of quality improvement and prespecifying efforts to train better models with these data.
Comment: What do you mean by a predictive model will be worse? worse that what?

Avoiding Bias Through Model Selection


How to tell what Operating System is running in HyperV VM with Powershell

Question: So here's the environment.
Host: Windows 10
Guests: Server 2012 and Server 2016
Purpose: Development system to automate pushing out builds to servers for testing during development.
I've got a Powershell function as part of this full build script that gets a remote PSSession for the VM I'm going to be working with. Since the VM is cloned dynamically from a base system, at this point I don't know what the OS in the VM is.
If it's a 2016 VM, I'd rather use Powershell Direct to connect to the VM.
$session = New-PSSession -VMName $VMName -Credential $VMCredentials

If it's 2012 I have to fall back to a WinRM session across the network. I've got the code to get the IP and make the connection. It works fine.
        $vm = Get-Vm -Name $VMName
    $ips = New-Object System.Collections.Generic.List[System.String]

    foreach ($adapter in $vm.NetworkAdapters)
    {
        foreach ($ip in $adapter.IPAddresses)
        {
            if($ip -like '*.*')
            {
                $ips.Add($ip)
            }
        }
    }

    $session = New-PSSession -ComputerName $ips[0] -Authentication Negotiate -Credential $VMCredentials

What I need is to know how to tell whether I should be running the Powershell Direct (2016 only) or the WinRM network based connection (2012 and older).
My thought is the Hyper-V cmdlets have to have some way to tell what OS is IN the VM. Maybe not. I'm open to other ways of solving this too. Thanks!
Comment: Besides googleing for soltuions, I tried a Try Catch block around the first method with the catch trying the second method. This still sent back an error from the cmdlet, so I tried -ErrorAction Ignore on the first one, and if $session was -eq $null, then use the second block. It still fails to run the second block.
Comment: Have you tried probing Hyper-V for details that might lead you to figure out the guest OS version?
Comment: I've looked through the object you get back from Get-VM, but I didn't see anything there.
Comment: Can't you use `Get-WMIObject -Class Win32_OperatingSystem` to find out what OS it's running then go from there?
Comment: I'm running this code on the Host not the Guest. This is the code that gets me the remote connection where I could run that (unless there's a way to use the WMI objects against a remote system).
Comment: Use `Get-WMIObject -Class Win32_OperatingSystem -ComputerName $VMName -Credential $VMCredentials`. You can replace the $VMName with an IP address if you want as well.
Comment: That gives a "No Such Interface Supported" error. It works locally, just not with a ComputerName attribute.
Comment: Are RPC services running on those servers?
Comment: @SamuelWarren How about the `IntegrationServicesVersion` property? The version of the IS should be a dead give away as to the VM's OS, as per [this](https://social.technet.microsoft.com/wiki/contents/articles/33796.hyper-v-integration-services-list-of-build-numbers.aspx) article. Not sure what the versions would be for 2016, but I'd think it will be 10.0.x, based on the OS build numbers.
Answer: Unfotunately Get-VM cmdlet does not give you any details on what OS the guest VM is running. Since you're trying to find out if the guest OS is either Windows Server 2016 or Windows Server 2012, you can use Get-WMIObject to retrieve that exact information.
Using the following command should bring you back the version number:
Get-WMIObject -Class Win32_OperatingSystem -ComputerName $VMName -Credential $VMCredentials | Select-Object *Version -ExpandProperty Version*

Windows 2012 is version 6.3.x while Windows 2016 is version 10.0.x.
Comment: I'm getting an RPC error... Which I think means this will work. I'll let you know.
Comment: Ok I got my RPC Server working correctly. This works like a charm!
Comment: There is another issue. You assume the VMName coming from the Get-VM is the same than the guest computer DNS name... This is not always the case,  I'm trying to find if the virtual machine is Linux but with a 'random' name.


How can I check the background color of a class using jquery?

Question: I have set the background color of a class using css, now I want to put it in a variable using jquery. Thanks
Answer: You may have to apply that class to a temporary element, and then extract the bgcolor of that element.
.cm { background-color:#990000 }

--
// creating an empty element and applying our class to it
var bgcolor = $("
").appendTo("body").addClass("cm").css("background-color");
alert(bgcolor); // rgb(153, 0, 0)

Comment: `$("").appendTo("body").addClass("cm").css("background-color").remove()`
Comment: ... and I rolled back my edit.  Only Firefox is able to determine the background color from a dummy element that is not part of the DOM.
Comment: I edited this answer so it demonstrates that there's actually no need to _append_ the dummy element to the document.  You can simply create a temporary div, add a style to it, and extract the background color.
Comment: I should have known better than to edit the answer before testing thoroughly... at least I eventually tested my own code and caught it!  For the record, if the dummy element is not part of the DOM, IE9 will return `'transparent'` and Chrome will return `''` in the above example.
Answer: If there is an element on the page using that class, you can do something like:
var backgroundColor = $('.classname').css('background-color');
But if nothing is using the class, I'm not familiar with any way to grab the color save from loading the .css file and parsing it in JavaScript (less than ideal).
Comment: No it's not there on the page
Answer: The problem is that jquery can't traverse the actual stylesheet (as far as I know), so if you have an element with two classes, you would have no way of knowing whether the color it returned was for the class you wanted or the other one. For instance:

.big {
   background-color: yellow;
}
.mean {
   background-color: blue;
}

The first one would be blue, but if you request the background color using:
 $(".big").css("background-color");

You would get blue, even though that class is set to yellow, since the first element is technically of the class big but it has a blue background.
I like Jonathan Sampson's idea. Create an element, make it invisible or offscreen, but give it an ID and the class you are wondering about. Then check the background color of that ID instead of checking by class:
 $("#colortest").css("background-color");

Answer: var $tmp = $('');
$('body').append($tmp).hide();
var color = $('.classname').css('background-color');
$tmp.remove();

EDIT: Applies the class to a hidden element.
Comment: See my comment regarding class conflict. With your example, there is no assurance that the element jquery grabs the color from is the one you created. I'd go with `var $tmp = $(''); and then set the var color to the ID.


How to go about creating a Java scheduled (repeating) app on AWS

Question: I want to write a basic Java app and have it run every 10 minutes on AWS (It will run a web service and check the returned data against data in a file which I also want to store on AWS (in S3 I think it must be stored).
Must I use AWS Data Pipeline and Task Runner to do this?
Many thanks
Answer: It's easier and cheaper to have a permanent instance with a cronjob for every ten minutes..


MFC: Reading entire file to buffer

Question: I've meddled with some code but I am unable to read the entire file properly...a lot of junk gets appended to the output. How do I fix this?
// wmfParser.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "wmfParser.h"
#include <cstring>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: MFC initialization failed\n"));
        nRetCode = 1;
    }
    else
    {
        // TODO: code your application's behavior here.
        CFile file;
        CFileException exp;
        if( !file.Open( _T("c:\\sample.txt"), CFile::modeRead, &exp ) ){
            exp.ReportError();
            cout<<'\n';
            cout<<"Aborting...";
            system("pause");
            return 0;
        }

        ULONGLONG dwLength = file.GetLength();
        cout<<"Length of file to read = " << dwLength << '\n';
        /*
        BYTE* buffer;
        buffer=(BYTE*)calloc(dwLength, sizeof(BYTE));
        file.Read(buffer, 25);
        char* str = (char*)buffer;
        cout<<"length of string : " << strlen(str) << '\n';
        cout<<"string from file: " << str << '\n';
        */

        char str[100];

        file.Read(str, sizeof(str));
        cout << "Data : " << str <<'\n';
        file.Close();
        cout<<"File was closed\n";

        //AfxMessageBox(_T("This is a test message box"));
        system("pause");
    }
    return nRetCode;
}

UPDATE:
specifically looking for guidance with respect to the commented code...will also like to hear other suggestions too...
Answer: Your string is not NULL terminated. You need to initialize the string str with memset(str,0, sizeof(str));
Answer: I think this might be closer to what you're looking for:
    /* first method */

    ULONGLONG dwLength = file.GetLength();
    cout << "Length of file to read = " << dwLength << '\n';

    // make room for whole file, plus null
    BYTE *buffer = (BYTE *) malloc(dwLength + 1);

    file.Read(buffer, dwLength); // read whole file
    *(buffer + dwLength) = '\0';   // add null

    cout << "length of string : " << strlen(buffer) << '\n';
    cout << "string from file: " << buffer << '\n';

    free(buffer);

    file.SeekToBegin(); // Back to the beginning

    /* second method */
    char str[dwLength + 1];

    file.Read(str, dwLength + 1);
    str[dwLength] = '\0';

    cout << "Data : " << str <<'\n';
    file.Close();

    cout << "File was closed\n";

MFC: Reading entire file to buffer


Example of a field embedding from K to K which is not an Automorphism.

Question: A field embedding from K to K is an injective homomorphism. What is an example of a field embedding which is not surjective (and therefore not an automorphism)?
Answer: Take a field $K$ and consider $K(x_1,x_2,\ldots)$, the field of rational functions in countably infinite variables with coefficients in $K$ (equivalently, a transcendental field extension of $K$ with countably infinite transcendence degree, and no non-trivial algebraic elements).
Now consider the embedding
$$
K(x_1,x_2,\ldots)\to K(x_1,x_2,\ldots)\\
1\mapsto 1\\
x_i\mapsto x_{i+1}
$$


error installing nltk supporting packages : nltk.download() in python

Question: I installed nltk package. Following that I am trying to download the supporting packages using nltk.download() and am getting error:
[Errno 11001] getaddrinfo

I tried changing server index as suggested by previous answers for this question but that didn't help me.
Can anyone please help me
Comment: Have you read this post : https://stackoverflow.com/questions/27750608/error-installing-nltk-supporting-packages-nltk-download?rq=1 ?
Comment: Are you behind a firewall? You need to set a proxy to pass through.
Comment: Thanks Wiktor  for your help , setting proxy solved error
Answer: Setting proxy solved my problem.


Uploading a CSV file with foreign key into Django

Question: I have uploaded two datasets (without foreign keys based on Service and Library models see below), but cannot upload the third which has foreign keys for the two other datasets.
First, I'm uploading them in the shell, by running this code in "python manage.py shell". My foreign key columns are service and library and connecting to service via 'cpt' and library via 'hid'.
These are the parts of the code not working
service=Service.objects.get(cpt=row['cpt']),
library=Library.objects.get(hid=row['hid'])

This is the full code:
from catalog.models import Service, Library, Price
# not including the intro - price dataset gets pulled in
with open('price.csv') as csvfile:
      reader = csv.DictReader(csvfile)
      for row in reader:
            p = Price(com_desc=row['com_desc'],service=Service.objects.get(cpt=row['cpt']),price_offer=row['price_offer'], comments=row['comments'], library=Library.objects.get[hid='hid'])
            p.save()

Here is the error that I get (updated):
 site-packages/django/db/models/query.py", line 399, in get
    self.model._meta.object_name
catalog.models.Service.DoesNotExist: Service matching query does not exist.

Here are my models: Service, Library and Price. As I said before, Service and Library are already uploaded, but struggling to upload Price because of the foreign keys.
# Service Model
class Service(models.Model):
    serviceid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular service in database')
    desc_us = models.TextField(blank=True, primary_key = True)
    cpt = models.IntegerField(default= 10000)
    price_std = models.DecimalField(max_digits=6, decimal_places=2, blank=True)

# Library Model
class Library(models.Model):
    hid = models.CharField(max_length = 8, null=True)
    name = models.CharField(max_length=200, primary_key=True)
    hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular hospital in database')
    address = models.CharField(max_length = 200, null = True)
    city = models.CharField(max_length = 50, null = True)
    state = models.CharField(max_length = 2, null=True)
    zipcode = models.CharField(max_length = 5, null=True)
    phone = models.CharField(max_length = 12, null=True)

# Price Model, Foreign Keys are; Service, Library (want to connect these by 'cpt' for service and 'hid' for library)
class Price(models.Model):
  priceid = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular service in database')
  com_desc = models.CharField(max_length = 200, blank = True, null = True)
  service = models.ForeignKey("Service", on_delete=models.SET_NULL, null=True)
  price_offer = models.DecimalField(max_digits=8, decimal_places=2, blank=True)
  comments = models.CharField(max_length = 200, blank = True, null =True)
  library = models.ForeignKey("Library", on_delete=models.SET_NULL, null=True)

Sample rows from price.csv
Answer: This line is clearly too condensed for debugging; try breaking it up:
p = Price(com_desc=row['com_desc'],service=Service.objects.get(row['cpt']),price_offer=row['price_offer'], comments=row['comments'], library=Library.objects.get['hid'])

One thing that stands out is that you probably mean this:
library=Library.objects.get(row['hid'])  # rather than .get['hid']

Other than that, I'd create and print out the individual fields separately to make sure they contain what you expect, before creating and trying to save the new Price object.
========
If there really is always one and only one Service per cpt and only one Library per hid, then using get() is fine. You should however formalize that by adding a unique constraint to the relevant model fields (if you get an error on adding the constraint, then the values are not unique after all).
If it doesn't matter which one you select when there are several, you can use this:
service = Service.objects.filter(row['cpt'])[0]

Note that this will throw an error if no records are found for a given cpt (but then get() would error as well if no matching object is found).
You can do the same with Library and hid.
Comment: Ths is what is causing the error: service=Service.objects.get(cpt=row['cpt']). Please help me debug this. The rest of the code, not freign keys works.
Comment: What is the content of `row['cpt']` when the error happens? And are you sure there can only be a single `Service` with that `cpt`? There is no unique constraint on `cpt` in your model, and `get()` throws an error (although I'd expect it to be a different one) when more than one object is returned by the query.
Comment: Then `get()` cannot work. You either need a unique identifier in the CSV data to find the one `Service` you want, or if you are content with *any* `Service` that has the correct `cpt`, you need to filter on `cpt` and then select one of potentially several `Service` objects.
Comment: Thanks! Could you show me how to go this. There are multiple prices for every cpt, but only one cpt for every price.
Comment: or at least give me some clues.
Comment: You've described the relationship between price and cpt, but what we need is the relationship between cpt and Service on the one hand, and hid and Library on the other hand. If there is no one-to-one relationship between them, you need to think about how you can select one Service/Library when the criterion you are using returns several of them. If in fact the relationship is one-to-one, see above on how to use filter rather than get.
Comment: cpt is a column in service, but is not the primary key. There are no duplicate cpts in the service table. This is exactly the same for library and hid. It's not a one to one it's many to one with (many prices with the same cpt in the Price table).
Comment: I tried your filter, but get the error - list index out of range
Comment: I tried your filter, but get the error - list index out of range
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189402/discussion-between-j-r-and-endre-both).