qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
13,788,114
|
Given the following Python (from <http://norvig.com/sudoku.html>)
```
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
cols = '123456789'
rows = 'ABCDEFGHI'
squares = cross(rows, cols)
```
This produces:
```
['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...]
```
As an exercise, I want to do the same in C++. Currently I have:
```
#include <iostream>
#include <map>
#include <vector>
using std::string;
using std::vector;
static vector<string> cross_string(const string &A, const string &B)
{
vector<string> result;
for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) {
for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) {
char s[] = {*itA, *itB, 0};
result.push_back(string(s));
}
}
return result;
}
int main(int argc, char** argv)
{
const char digits[] = "123456789";
const char rows[] = "ABCDEFGHI";
vector<string> res = cross_string(rows, digits);
for (vector<string>::const_iterator it = res.begin();
it != res.end(); ++it) {
std::cout << *it << std::endl;
}
}
```
This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list...
---
Edit:
Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.
|
2012/12/09
|
[
"https://Stackoverflow.com/questions/13788114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163625/"
] |
Well it's shorter to just present the code than to explain:
```
#include <iostream> // std::wcout, std::endl
#include <string> // std::string
#include <utility> // std::begin, std::end
#include <vector>
using namespace std;
string sum( char const a, char const b ) { return string() + a + b; }
template< class Container >
auto cross( Container const& a, Container const& b )
-> vector< decltype( sum( *begin( a ), *begin( b ) ) ) >
{
typedef decltype( sum( *begin( a ), *begin( b ) ) ) ResultItem;
vector< ResultItem > result;
for( auto&& itemA : a ) for( auto&& itemB : b )
{
result.push_back( sum( itemA, itemB ) );
}
return result;
}
wostream& operator<<( wostream& stream, string const& s )
{
return (stream << s.c_str());
}
template< class Item >
wostream& operator<<( wostream& stream, vector<Item> const& v )
{
stream << "[";
bool isFirstItem = true;
for( auto&& item : v )
{
if( !isFirstItem ) { stream << ", "; }
stream << item;
isFirstItem = false;
}
stream << "]";
return stream;
}
int main()
{
string const cols = "123456789";
string const rows = "ABCDEFGHI";
auto const squares = cross( cols, rows );
wcout << squares << endl;
}
```
|
You could certainly make this generic:
```
template <class InIt1, class InIt2, class OutIt>
void cross_product(InIt1 b1, InIt1 e1, InIt2 b2, InIt2 e2, OutIt out) {
for (auto i=b1; i != e1; ++i)
for (auto j=b2; j != e2; ++j)
*out++ = std::make_pair(*i, *j);
}
```
Note that you don't generally want the template parameters to be the types of the objects in the collections, but the types of iterators to the collections. For example, you could use this like this:
```
std::ostream &operator<<(std::ostream &os, std::pair<char, int> const &d) {
return os << d.first << d.second;
}
int main() {
std::vector<char> a{'A', 'B', 'C', 'D'};
std::vector<int> b{ 1, 2, 3, 4};
cross_product(a.begin(), a.end(), b.begin(), b.end(),
infix_ostream_iterator<std::pair<char, int> >(std::cout, ", "));
return 0;
}
```
...which should produce output like this:
```
A1, A2, A3, A4, B1, B2, B3, B4, C1, C2, C3, C4, D1, D2, D3, D4
```
Also note that I've used some C++11 features throughout most of this code. If you're using an older compiler (or one from Microsoft) it'll need a bit of editing.
|
13,788,114
|
Given the following Python (from <http://norvig.com/sudoku.html>)
```
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
cols = '123456789'
rows = 'ABCDEFGHI'
squares = cross(rows, cols)
```
This produces:
```
['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...]
```
As an exercise, I want to do the same in C++. Currently I have:
```
#include <iostream>
#include <map>
#include <vector>
using std::string;
using std::vector;
static vector<string> cross_string(const string &A, const string &B)
{
vector<string> result;
for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) {
for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) {
char s[] = {*itA, *itB, 0};
result.push_back(string(s));
}
}
return result;
}
int main(int argc, char** argv)
{
const char digits[] = "123456789";
const char rows[] = "ABCDEFGHI";
vector<string> res = cross_string(rows, digits);
for (vector<string>::const_iterator it = res.begin();
it != res.end(); ++it) {
std::cout << *it << std::endl;
}
}
```
This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list...
---
Edit:
Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.
|
2012/12/09
|
[
"https://Stackoverflow.com/questions/13788114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163625/"
] |
Weirdly enough, `cross_product` is missing from the C++ algorithms library. It can easily be added but as Jerry’s and Alf’s answers show, opinions differ on how to do it best. In fact, I’d do it different still. Jerry’s interface conforms to that of the other C++ algorithms but he didn’t abstract away the cross product operation, which I’d do thusly:
```
template <typename InputIt1,
typename InputIt2,
typename OutputIt,
typename F>
void cross_product(InputIt1 begin1,
InputIt1 end1,
InputIt2 begin2,
InputIt2 end2,
OutputIt out,
F f) {
for (auto i = begin1; i != end1; ++i)
for (auto j = begin2; j != end2; ++j)
*out++ = f(*i, *j);
}
```
The call, in your example, would then look as follows:
```
auto digits = "1234546789";
auto chars = "ABCDEFGHI";
vector<string> result;
cross_product(digits, digits + strlen(digits),
chars, chars + strlen(chars),
back_inserter(result),
[](char a, char b) { return string() + a + b; });
```
(Don’t I just love C++11? Yes, I do.)
In a proper library I’d offer a second overload which supplies a default `f` operation which creates a tuple similar to what Jerry’s code does. It would even be thinkable to abstract this further to allow more than two ranges – after all, the Python list comprehension allows you to iterate over more than two ranges).
|
Well it's shorter to just present the code than to explain:
```
#include <iostream> // std::wcout, std::endl
#include <string> // std::string
#include <utility> // std::begin, std::end
#include <vector>
using namespace std;
string sum( char const a, char const b ) { return string() + a + b; }
template< class Container >
auto cross( Container const& a, Container const& b )
-> vector< decltype( sum( *begin( a ), *begin( b ) ) ) >
{
typedef decltype( sum( *begin( a ), *begin( b ) ) ) ResultItem;
vector< ResultItem > result;
for( auto&& itemA : a ) for( auto&& itemB : b )
{
result.push_back( sum( itemA, itemB ) );
}
return result;
}
wostream& operator<<( wostream& stream, string const& s )
{
return (stream << s.c_str());
}
template< class Item >
wostream& operator<<( wostream& stream, vector<Item> const& v )
{
stream << "[";
bool isFirstItem = true;
for( auto&& item : v )
{
if( !isFirstItem ) { stream << ", "; }
stream << item;
isFirstItem = false;
}
stream << "]";
return stream;
}
int main()
{
string const cols = "123456789";
string const rows = "ABCDEFGHI";
auto const squares = cross( cols, rows );
wcout << squares << endl;
}
```
|
13,788,114
|
Given the following Python (from <http://norvig.com/sudoku.html>)
```
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
cols = '123456789'
rows = 'ABCDEFGHI'
squares = cross(rows, cols)
```
This produces:
```
['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...]
```
As an exercise, I want to do the same in C++. Currently I have:
```
#include <iostream>
#include <map>
#include <vector>
using std::string;
using std::vector;
static vector<string> cross_string(const string &A, const string &B)
{
vector<string> result;
for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) {
for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) {
char s[] = {*itA, *itB, 0};
result.push_back(string(s));
}
}
return result;
}
int main(int argc, char** argv)
{
const char digits[] = "123456789";
const char rows[] = "ABCDEFGHI";
vector<string> res = cross_string(rows, digits);
for (vector<string>::const_iterator it = res.begin();
it != res.end(); ++it) {
std::cout << *it << std::endl;
}
}
```
This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list...
---
Edit:
Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.
|
2012/12/09
|
[
"https://Stackoverflow.com/questions/13788114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163625/"
] |
Weirdly enough, `cross_product` is missing from the C++ algorithms library. It can easily be added but as Jerry’s and Alf’s answers show, opinions differ on how to do it best. In fact, I’d do it different still. Jerry’s interface conforms to that of the other C++ algorithms but he didn’t abstract away the cross product operation, which I’d do thusly:
```
template <typename InputIt1,
typename InputIt2,
typename OutputIt,
typename F>
void cross_product(InputIt1 begin1,
InputIt1 end1,
InputIt2 begin2,
InputIt2 end2,
OutputIt out,
F f) {
for (auto i = begin1; i != end1; ++i)
for (auto j = begin2; j != end2; ++j)
*out++ = f(*i, *j);
}
```
The call, in your example, would then look as follows:
```
auto digits = "1234546789";
auto chars = "ABCDEFGHI";
vector<string> result;
cross_product(digits, digits + strlen(digits),
chars, chars + strlen(chars),
back_inserter(result),
[](char a, char b) { return string() + a + b; });
```
(Don’t I just love C++11? Yes, I do.)
In a proper library I’d offer a second overload which supplies a default `f` operation which creates a tuple similar to what Jerry’s code does. It would even be thinkable to abstract this further to allow more than two ranges – after all, the Python list comprehension allows you to iterate over more than two ranges).
|
You could certainly make this generic:
```
template <class InIt1, class InIt2, class OutIt>
void cross_product(InIt1 b1, InIt1 e1, InIt2 b2, InIt2 e2, OutIt out) {
for (auto i=b1; i != e1; ++i)
for (auto j=b2; j != e2; ++j)
*out++ = std::make_pair(*i, *j);
}
```
Note that you don't generally want the template parameters to be the types of the objects in the collections, but the types of iterators to the collections. For example, you could use this like this:
```
std::ostream &operator<<(std::ostream &os, std::pair<char, int> const &d) {
return os << d.first << d.second;
}
int main() {
std::vector<char> a{'A', 'B', 'C', 'D'};
std::vector<int> b{ 1, 2, 3, 4};
cross_product(a.begin(), a.end(), b.begin(), b.end(),
infix_ostream_iterator<std::pair<char, int> >(std::cout, ", "));
return 0;
}
```
...which should produce output like this:
```
A1, A2, A3, A4, B1, B2, B3, B4, C1, C2, C3, C4, D1, D2, D3, D4
```
Also note that I've used some C++11 features throughout most of this code. If you're using an older compiler (or one from Microsoft) it'll need a bit of editing.
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Your selection list in the first condition of your `if` statement is the problem.
If `opt` happens to be `es`, for example, then
```
if opt == 'es':
opt = "ESP:"
```
will change that to `ESP:`.
```
if opt in ["es","la","en","ar","fr"] and extent == "begin":
```
can then never be `True` (when you're using `and` instead of `or`).
If you change that line to something like
```
if opt in ["ESP:","LAT:","ENG:","ar","fr"] and extent == "begin":
```
it might work (if the code you've shown is all that's relevant to the problem).
|
**AND**
To become condition True by **AND Operator**, required **True** result from the **all conditions**.
**OR**
To become condition True by **OR Operator**, required **True** result from the any **one condition**.
**E.g.**
```
In [1]: True and True
Out[1]: True
In [2]: True and False
Out[2]: False
In [3]: True or False
Out[3]: True
```
---
In your code, print following statements:
```
print "Debug 1: opt value", opt
print "Debug 2: extent value", extent
```
**Why use same variable name again??**
If value of `opt` is `es` then if condition `if opt == 'es':` is `True` and `opt` variable is again assign to vale `ESP:`.
And in your final if statement you check `opt in ["es","la","en","ar","fr"]` , so which is always `False`.
```
opt = child.get('desc')
# ^^
extent = child.get('extent')
if opt == 'es':
opt = "ESP:"
# ^^
elif opt == "la":
opt = "LAT:"
elif opt == "en":
```
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Unless the output from the first line of code is `"ar"` or `"fr"` (or something else not in the `if-elif` conditions), you are over-writing the `opt` variable. Consider re-naming the 'new' `opt` to something else, like follows:
```
opt = child.get('desc')
extent = child.get('extent')
if opt == 'es':
opt2 = "ESP:"
elif opt == "la":
opt2 = "LAT:"
elif opt == "en":
opt2 = "ENG:"
# Check variable values
print "opt: ", opt
print "opt2: ", opt2
if opt in ["es","la","en","ar","fr"] and extent == "begin":
print time, opt2+(" " + opt2).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
I am not sure what exactly you wish to achieve from the code, but the above will at least get your `if-else` condition met if the original `child.get('desc')` condition returns a string that exists in the list.
|
**AND**
To become condition True by **AND Operator**, required **True** result from the **all conditions**.
**OR**
To become condition True by **OR Operator**, required **True** result from the any **one condition**.
**E.g.**
```
In [1]: True and True
Out[1]: True
In [2]: True and False
Out[2]: False
In [3]: True or False
Out[3]: True
```
---
In your code, print following statements:
```
print "Debug 1: opt value", opt
print "Debug 2: extent value", extent
```
**Why use same variable name again??**
If value of `opt` is `es` then if condition `if opt == 'es':` is `True` and `opt` variable is again assign to vale `ESP:`.
And in your final if statement you check `opt in ["es","la","en","ar","fr"]` , so which is always `False`.
```
opt = child.get('desc')
# ^^
extent = child.get('extent')
if opt == 'es':
opt = "ESP:"
# ^^
elif opt == "la":
opt = "LAT:"
elif opt == "en":
```
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
**AND**
To become condition True by **AND Operator**, required **True** result from the **all conditions**.
**OR**
To become condition True by **OR Operator**, required **True** result from the any **one condition**.
**E.g.**
```
In [1]: True and True
Out[1]: True
In [2]: True and False
Out[2]: False
In [3]: True or False
Out[3]: True
```
---
In your code, print following statements:
```
print "Debug 1: opt value", opt
print "Debug 2: extent value", extent
```
**Why use same variable name again??**
If value of `opt` is `es` then if condition `if opt == 'es':` is `True` and `opt` variable is again assign to vale `ESP:`.
And in your final if statement you check `opt in ["es","la","en","ar","fr"]` , so which is always `False`.
```
opt = child.get('desc')
# ^^
extent = child.get('extent')
if opt == 'es':
opt = "ESP:"
# ^^
elif opt == "la":
opt = "LAT:"
elif opt == "en":
```
|
This is an operator precedence problem. You expect the code to work as:
```
if (opt in ["es","la","en","ar","fr"]) and (extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
But it works as
```
if opt in (["es","la","en","ar","fr"] and extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
which evaluates to different values than you expect.
Try the parentheses in the first code piece.
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Unless the output from the first line of code is `"ar"` or `"fr"` (or something else not in the `if-elif` conditions), you are over-writing the `opt` variable. Consider re-naming the 'new' `opt` to something else, like follows:
```
opt = child.get('desc')
extent = child.get('extent')
if opt == 'es':
opt2 = "ESP:"
elif opt == "la":
opt2 = "LAT:"
elif opt == "en":
opt2 = "ENG:"
# Check variable values
print "opt: ", opt
print "opt2: ", opt2
if opt in ["es","la","en","ar","fr"] and extent == "begin":
print time, opt2+(" " + opt2).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
I am not sure what exactly you wish to achieve from the code, but the above will at least get your `if-else` condition met if the original `child.get('desc')` condition returns a string that exists in the list.
|
Your selection list in the first condition of your `if` statement is the problem.
If `opt` happens to be `es`, for example, then
```
if opt == 'es':
opt = "ESP:"
```
will change that to `ESP:`.
```
if opt in ["es","la","en","ar","fr"] and extent == "begin":
```
can then never be `True` (when you're using `and` instead of `or`).
If you change that line to something like
```
if opt in ["ESP:","LAT:","ENG:","ar","fr"] and extent == "begin":
```
it might work (if the code you've shown is all that's relevant to the problem).
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Your selection list in the first condition of your `if` statement is the problem.
If `opt` happens to be `es`, for example, then
```
if opt == 'es':
opt = "ESP:"
```
will change that to `ESP:`.
```
if opt in ["es","la","en","ar","fr"] and extent == "begin":
```
can then never be `True` (when you're using `and` instead of `or`).
If you change that line to something like
```
if opt in ["ESP:","LAT:","ENG:","ar","fr"] and extent == "begin":
```
it might work (if the code you've shown is all that's relevant to the problem).
|
When `opt` is one of these: `"es", "la", "en"`
then the value of `opt` is changed, and this:
`if opt in ["es","la","en","ar","fr"] and extent == "begin":`
won't pass, because `opt` is wrong.
I guess `extent` is equal `"begin"`, so if u swap `and` with `or` it will pass, as one of the statements is correct. Try to remove this big `if/elif/elif` and try to run it again with `and`. It should pass.
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Your selection list in the first condition of your `if` statement is the problem.
If `opt` happens to be `es`, for example, then
```
if opt == 'es':
opt = "ESP:"
```
will change that to `ESP:`.
```
if opt in ["es","la","en","ar","fr"] and extent == "begin":
```
can then never be `True` (when you're using `and` instead of `or`).
If you change that line to something like
```
if opt in ["ESP:","LAT:","ENG:","ar","fr"] and extent == "begin":
```
it might work (if the code you've shown is all that's relevant to the problem).
|
This is an operator precedence problem. You expect the code to work as:
```
if (opt in ["es","la","en","ar","fr"]) and (extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
But it works as
```
if opt in (["es","la","en","ar","fr"] and extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
which evaluates to different values than you expect.
Try the parentheses in the first code piece.
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Unless the output from the first line of code is `"ar"` or `"fr"` (or something else not in the `if-elif` conditions), you are over-writing the `opt` variable. Consider re-naming the 'new' `opt` to something else, like follows:
```
opt = child.get('desc')
extent = child.get('extent')
if opt == 'es':
opt2 = "ESP:"
elif opt == "la":
opt2 = "LAT:"
elif opt == "en":
opt2 = "ENG:"
# Check variable values
print "opt: ", opt
print "opt2: ", opt2
if opt in ["es","la","en","ar","fr"] and extent == "begin":
print time, opt2+(" " + opt2).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
I am not sure what exactly you wish to achieve from the code, but the above will at least get your `if-else` condition met if the original `child.get('desc')` condition returns a string that exists in the list.
|
When `opt` is one of these: `"es", "la", "en"`
then the value of `opt` is changed, and this:
`if opt in ["es","la","en","ar","fr"] and extent == "begin":`
won't pass, because `opt` is wrong.
I guess `extent` is equal `"begin"`, so if u swap `and` with `or` it will pass, as one of the statements is correct. Try to remove this big `if/elif/elif` and try to run it again with `and`. It should pass.
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
Unless the output from the first line of code is `"ar"` or `"fr"` (or something else not in the `if-elif` conditions), you are over-writing the `opt` variable. Consider re-naming the 'new' `opt` to something else, like follows:
```
opt = child.get('desc')
extent = child.get('extent')
if opt == 'es':
opt2 = "ESP:"
elif opt == "la":
opt2 = "LAT:"
elif opt == "en":
opt2 = "ENG:"
# Check variable values
print "opt: ", opt
print "opt2: ", opt2
if opt in ["es","la","en","ar","fr"] and extent == "begin":
print time, opt2+(" " + opt2).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
I am not sure what exactly you wish to achieve from the code, but the above will at least get your `if-else` condition met if the original `child.get('desc')` condition returns a string that exists in the list.
|
This is an operator precedence problem. You expect the code to work as:
```
if (opt in ["es","la","en","ar","fr"]) and (extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
But it works as
```
if opt in (["es","la","en","ar","fr"] and extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
which evaluates to different values than you expect.
Try the parentheses in the first code piece.
|
30,884,008
|
I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bsingh/python_files/lib/Site.py", line 85, in monitor
self.update1()
File "/home/bsingh/python_files/lib/Site.py", line 78, in update1
for entry in new_pastes[::-1]:
TypeError: 'NoneType' object has no attribute '__getitem__'
```
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] |
When `opt` is one of these: `"es", "la", "en"`
then the value of `opt` is changed, and this:
`if opt in ["es","la","en","ar","fr"] and extent == "begin":`
won't pass, because `opt` is wrong.
I guess `extent` is equal `"begin"`, so if u swap `and` with `or` it will pass, as one of the statements is correct. Try to remove this big `if/elif/elif` and try to run it again with `and`. It should pass.
|
This is an operator precedence problem. You expect the code to work as:
```
if (opt in ["es","la","en","ar","fr"]) and (extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
But it works as
```
if opt in (["es","la","en","ar","fr"] and extent == "begin"):
print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])
```
which evaluates to different values than you expect.
Try the parentheses in the first code piece.
|
17,559,257
|
I am using the following code to send email from unix.
Code
```
#!/usr/bin/python
import os
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "myname@company.com")
p.write("To: %s\n" % "yourname@company.com")
p.write("Subject: My Subject \n")
p.write("\n") # blank line separating headers from body
p.write("body of the mail")
status = p.close()
if status != 0:
print "Mail Sent Successfully", status
sendMail()
```
I am not sure how to add attachment to this email (attachment being on a different directory /my/new/dir/)
|
2013/07/09
|
[
"https://Stackoverflow.com/questions/17559257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392233/"
] |
Sendmail is an extremely simplistic program. It knows how to send a blob of text over smtp. If you want to have attachments, you're going to have to do the work of converting them into a blob of text and using (in your example) p.write() to add them into the message.
That's hard - but you can use the `email` module (part of python core) to do a lot of the work for you.
Even better, you can use `smtplib` (also part of core) to handle sending the mail.
Check out <http://docs.python.org/2/library/email-examples.html#email-examples> for a worked example showing how to send a mail with attachments using `email` and `smtplib`
|
I normally use the following to send a file "file\_name.dat" as attachment:
```
uuencode file_name.dat file_name.dat | mail -s "Subject line" arnab.bhagabati@gmail.com
```
|
17,559,257
|
I am using the following code to send email from unix.
Code
```
#!/usr/bin/python
import os
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "myname@company.com")
p.write("To: %s\n" % "yourname@company.com")
p.write("Subject: My Subject \n")
p.write("\n") # blank line separating headers from body
p.write("body of the mail")
status = p.close()
if status != 0:
print "Mail Sent Successfully", status
sendMail()
```
I am not sure how to add attachment to this email (attachment being on a different directory /my/new/dir/)
|
2013/07/09
|
[
"https://Stackoverflow.com/questions/17559257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392233/"
] |
Use the `email.mime` package to create your mail instead of trying to generate it manually, it will save you a lot of trouble.
For example, sending a text message with an attachment could be as simple as:
```
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg['From'] = 'fromaddress'
msg['To'] = 'toaddres'
msg['Subject'] = 'subject'
msg.attach(MIMEText('your text message'))
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), 'subtype')
attachment['Content-Disposition'] = 'attachment; filename="%s";' % filename
msg.attach(attachment)
message = msg.as_string()
```
Then you can write the message to sendmail, or use smtplib to send it.
`'subtype'` should either be replaced with the mime subtype of the attached document, or left out to send the attachment with the default type of `application/octet-stream`. Or if you know your file is text, you can use `MIMEText` instead of `MIMEApplication`.
|
I normally use the following to send a file "file\_name.dat" as attachment:
```
uuencode file_name.dat file_name.dat | mail -s "Subject line" arnab.bhagabati@gmail.com
```
|
58,880,450
|
How might I remove duplicate lines from a file and also the unique related to this duplicate?
**Example:**
Input file:
```
line 1 : Messi , 1
line 2 : Messi , 2
line 3 : CR7 , 2
```
I want the output file to be:
```
line 1 : CR7 , 2
```
Just ( " CR7 , 2 " I want to delete duplicate lines and also the unique related to this duplicate)
The deletion depends on the first row if there is a match in the first row I want to delete this line
How to do this in python
with this code what to edit on it :
```
lines_seen = set() # holds lines already seen
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
```
What is the best way to do this job?
|
2019/11/15
|
[
"https://Stackoverflow.com/questions/58880450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12379359/"
] |
Have you tried `Counter`?
This works for example:
```
import collections
a = [1, 1, 2]
out = [k for k, v in collections.Counter(a).items() if v == 1]
print(out)
```
Output: `[2]`
Or with a longer example:
```
import collections
a = [1, 1, 1, 2, 4, 4, 4, 5, 3]
out = [k for k, v in collections.Counter(a).items() if v == 1]
print(out)
```
Output: `[2, 5, 3]`
EDIT:
-----
Since you don't have a list at the beginning there are two ways, depending on the file size you should use the first for small enough files (otherwise you might run in memory problems) or the second one for large files.
Read file as list and use previous answer:
==========================================
```
import collections
lines = [line for line in open(infilename)]
out = [k for k, v in collections.Counter(lines).items() if v == 1]
with open(outfilename, 'w') as outfile:
for o in out:
outfile.write(o)
```
The first line reads your file completely as a list. This means, that really large files would be loaded in your memory. If you have to large files you can go ahead and use a sort of "blacklist":
Using blacklist:
================
```
lines_seen = set() # holds lines already seen
blacklist = set()
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
if line not in lines_seen and line not in blacklist: # not a duplicate
lines_seen.add(line)
else:
lines_seen.discard(line)
blacklist.add(line)
for l in lines_seen:
outfile.write(l)
outfile.close()
```
Here you add all lines to the set and only write the set to the file at the end. The blacklist remembers all multiple occurrences and therefore you do not write multiple lines even once. You can't do it in one go, to read and write since you do not know, if there comes the same line a second time. If you have further information (like multiple lines always come continuously) you could maybe do it differently
EDIT 2
------
If you want to do it depending on the first part:
```
firsts_seen = set()
lines_seen = set() # holds lines already seen
blacklist = set()
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
first = line.split(',')[0]
if first not in firsts_seen and first not in blacklist: # not a duplicate
lines_seen.add(line)
firsts_seen.add(first)
else:
lines_seen.discard(line)
firsts_seen.discard(first)
blacklist.add(first)
print(len(lines_seen))
for l in lines_seen:
outfile.write(l)
outfile.close()
```
P.S.: By now I have just been adding code, there might be a better way
For example with a dict:
```
lines_dict = {}
for line in open(infilename, 'r'):
if line.split(',')[0] not in lines_dict:
lines_dict[line.split(',')[0]] = [line]
else:
lines_dict[line.split(',')[0]].append(line)
with open(outfilename, 'w') as outfile:
for key, value in lines_dict.items():
if len(value) == 1:
outfile.write(value[0])
```
|
Given your input you can do something like this:
```
seen = {} # key maps to index
double_seen = set()
with open('input.txt') as f:
for line in f:
_, key = line.split(':')
key = key.strip()
if key not in seen: # Have not seen this yet?
seen[key] = line # Then add it to the dictionary
else:
double_seen.add(key) # Else we have seen this more thane once
# Now we can just write back to a different file
with open('output.txt', 'w') as f2:
for key in set(seen.keys()) - double_seen:
f2.write(seen[key])
```
Input I used:
```
line 1 : Messi
line 2 : Messi
line 3 : CR7
```
Output:
```
line 3 : CR7
```
Note this solution assumes Python3.7+ since it assumes dictionaries are in insertion order.
|
67,194,174
|
I want to write a python code were the output will be something like this
[[1],[1,2],[1,2,3], … [1,2,3, … ]]
I have this code and has the similar output but the only difference is that it prints all the cases
for example
if I say that the range is 3 it prints
[[1], [1, 2], [1, 3], [1, 2, 3]]
and not
[[1], [1, 2], [1, 2, 3]]
This is my code
```
def sub_lists(l):
base = [1]
lists = [base]
for i in range(2, l+1):
orig = lists[:]
new = i
for j in range(len(lists)):
lists[j] = lists[j] + [new]
lists = orig + lists
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
```
|
2021/04/21
|
[
"https://Stackoverflow.com/questions/67194174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300391/"
] |
How about using `list comprehension`?
For example:
```
num = 3
print([[*range(1, i + 1)] for i in range(1, num + 1)])
```
Output:
```
[[1], [1, 2], [1, 2, 3]]
```
|
You should not use a loop inside loops if you intend to add a single number at the end of it only.
```
def copyBase(lst):
return lst[:]
def sub_lists(l):
base = [1]
lists = []
for i in range(1, l+1):
lists += [copyBase(base),]
base += [i+1]
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
```
|
67,194,174
|
I want to write a python code were the output will be something like this
[[1],[1,2],[1,2,3], … [1,2,3, … ]]
I have this code and has the similar output but the only difference is that it prints all the cases
for example
if I say that the range is 3 it prints
[[1], [1, 2], [1, 3], [1, 2, 3]]
and not
[[1], [1, 2], [1, 2, 3]]
This is my code
```
def sub_lists(l):
base = [1]
lists = [base]
for i in range(2, l+1):
orig = lists[:]
new = i
for j in range(len(lists)):
lists[j] = lists[j] + [new]
lists = orig + lists
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
```
|
2021/04/21
|
[
"https://Stackoverflow.com/questions/67194174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300391/"
] |
*output will be something like this [[1],[1,2],[1,2,3], … [1,2,3, … ]]*
You might combine `range` with `list` comprehension to get desired result, for example for 5:
```
n = 5
sublists = [list(range(1,i+1)) for i in range(1,n+1)]
print(sublists)
```
output
```
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
```
Note that range is inclusive-exclusive, thus these `+1`.
|
You should not use a loop inside loops if you intend to add a single number at the end of it only.
```
def copyBase(lst):
return lst[:]
def sub_lists(l):
base = [1]
lists = []
for i in range(1, l+1):
lists += [copyBase(base),]
base += [i+1]
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
```
|
67,194,174
|
I want to write a python code were the output will be something like this
[[1],[1,2],[1,2,3], … [1,2,3, … ]]
I have this code and has the similar output but the only difference is that it prints all the cases
for example
if I say that the range is 3 it prints
[[1], [1, 2], [1, 3], [1, 2, 3]]
and not
[[1], [1, 2], [1, 2, 3]]
This is my code
```
def sub_lists(l):
base = [1]
lists = [base]
for i in range(2, l+1):
orig = lists[:]
new = i
for j in range(len(lists)):
lists[j] = lists[j] + [new]
lists = orig + lists
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
```
|
2021/04/21
|
[
"https://Stackoverflow.com/questions/67194174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300391/"
] |
How about using `list comprehension`?
For example:
```
num = 3
print([[*range(1, i + 1)] for i in range(1, num + 1)])
```
Output:
```
[[1], [1, 2], [1, 2, 3]]
```
|
Try this
```
def sub_lists(l):
lists = []
for i in range(l):
sublist = [1]
for i2 in range(i):
sublist.append(i2+2)
lists.append(sublist)
return lists
```
**Implementation With User Input**
```
def sub_lists(l):
lists = []
for i in range(l):
sublist = [1]
for i2 in range(i):
sublist.append(i2+2)
lists.append(sublist)
return lists
input_num = int(input('Please Enter a Number: '))
results = sub_lists(input_num)
for i in results:
for i2 in i:
print(str(i2)+' ',end='')
print('')
```
|
67,194,174
|
I want to write a python code were the output will be something like this
[[1],[1,2],[1,2,3], … [1,2,3, … ]]
I have this code and has the similar output but the only difference is that it prints all the cases
for example
if I say that the range is 3 it prints
[[1], [1, 2], [1, 3], [1, 2, 3]]
and not
[[1], [1, 2], [1, 2, 3]]
This is my code
```
def sub_lists(l):
base = [1]
lists = [base]
for i in range(2, l+1):
orig = lists[:]
new = i
for j in range(len(lists)):
lists[j] = lists[j] + [new]
lists = orig + lists
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
```
|
2021/04/21
|
[
"https://Stackoverflow.com/questions/67194174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300391/"
] |
*output will be something like this [[1],[1,2],[1,2,3], … [1,2,3, … ]]*
You might combine `range` with `list` comprehension to get desired result, for example for 5:
```
n = 5
sublists = [list(range(1,i+1)) for i in range(1,n+1)]
print(sublists)
```
output
```
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
```
Note that range is inclusive-exclusive, thus these `+1`.
|
Try this
```
def sub_lists(l):
lists = []
for i in range(l):
sublist = [1]
for i2 in range(i):
sublist.append(i2+2)
lists.append(sublist)
return lists
```
**Implementation With User Input**
```
def sub_lists(l):
lists = []
for i in range(l):
sublist = [1]
for i2 in range(i):
sublist.append(i2+2)
lists.append(sublist)
return lists
input_num = int(input('Please Enter a Number: '))
results = sub_lists(input_num)
for i in results:
for i2 in i:
print(str(i2)+' ',end='')
print('')
```
|
58,105,181
|
I'm using databricks-connect on mac using pycharm but after I finished the configuration and tried to run `databricks-connect test`, I got the following error and have no idea what the problem is. I followed this documentation: <https://docs.databricks.com/user-guide/dev-tools/db-connect.html>
The error message is as below:
```
scala> spa
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/bin/databricks-connect", line 11, in
load_entry_point('databricks-connect==5.3.1', 'console_scripts', 'databricks-connect')()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyspark/databricks_connect.py", line 244, in main
test()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyspark/databricks_connect.py", line 213, in test
raise ValueError("Scala command failed to produce correct result")
ValueError: Scala command failed to produce correct result
```
|
2019/09/25
|
[
"https://Stackoverflow.com/questions/58105181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6279751/"
] |
Maybe your Java/Python version does not comply. Check your cluster, which Python version does it use (in my case it was 3.5).
And what's most important: check which JDK version do you have on your computer.
In my case, I've had the latest one, which was not supported by `databricks-connect`. It needs to run on JDK 8.
|
To ignore the RUNTIME version, export an environment variable that resolves:
export DEBUG\_IGNORE\_VERSION\_MISMATCH=1
|
58,105,181
|
I'm using databricks-connect on mac using pycharm but after I finished the configuration and tried to run `databricks-connect test`, I got the following error and have no idea what the problem is. I followed this documentation: <https://docs.databricks.com/user-guide/dev-tools/db-connect.html>
The error message is as below:
```
scala> spa
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/bin/databricks-connect", line 11, in
load_entry_point('databricks-connect==5.3.1', 'console_scripts', 'databricks-connect')()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyspark/databricks_connect.py", line 244, in main
test()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyspark/databricks_connect.py", line 213, in test
raise ValueError("Scala command failed to produce correct result")
ValueError: Scala command failed to produce correct result
```
|
2019/09/25
|
[
"https://Stackoverflow.com/questions/58105181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6279751/"
] |
I would make sure you are using the right version of the Databricks Runtime (DB Connect only currently supports 5.1-5.5). Since these is a limit on the DBR that works with DB connect, you'll have to make sure you match the python version as well (for the base Databricks runtime, I believe it is 3.5.x).
|
To ignore the RUNTIME version, export an environment variable that resolves:
export DEBUG\_IGNORE\_VERSION\_MISMATCH=1
|
25,331,758
|
I am writing a script to start and background a process inside a vagrant machine. It seems like every time the script ends and the ssh session ends, the background process also ends.
Here's the command I am running:
`vagrant ssh -c "cd /vagrant/src; nohup python hello.py > hello.out > 2>&1 &"`
`hello.py` is actually just a flask development server. If I were to login to ssh interactively and run the `nohup` command manually, after I close the session, the server will continue to run. However, if I were to run it via `vagrant ssh -c`, it's almost as if the command never ran at all (i.e. no hello.out file created). What is the difference between running it manually and through vagrant ssh -c, and how to fix it so that it works?
|
2014/08/15
|
[
"https://Stackoverflow.com/questions/25331758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3667561/"
] |
I faced the same problem when trying to run Django application as a daemon. I don't know why, but adding a "sleep 1" behind works for me.
```
vagrant ssh -c "nohup python manage.py runserver & sleep 1"
```
|
Running nohup inside the ssh command did not work for me when running wireshark. This did:
```
nohup vagrant ssh -c "wireshark" &
```
|
46,901,975
|
I am new to this whole python and the data mining.
Let's say I have a list of string called data
```
data[0] = ['I want to make everything lowercase']
data[1] = ['How Do I Do It']
data[2] = ['With A Large DataSet']
```
and so on. My len(data) gives 50000.
I have tried
```
{k.lower(): v for k, v in data.items()}
```
and it gives me error saying that 'list' object has no attribute 'items'.
and I have also tried using .lower() and it is giving me the same AtrributeError.
How do I recursively call the lower() function in all the data[:50000] to make all the of strings in the data to all lowercase?
EDIT:
For more details: I have a json file with datas such as:
```
{'review/a': 1.0, 'review/b':2.0, 'review/c':This IS the PART where I want to make all loWerCASE}
```
Then I call a function to get the specific reviews that I want to make all lower case to
```
def lowerCase(datum):
feat = [datum['review/c']]
return feat
lowercase = [lowercase(d) for d in data]
```
Now that I have all the 'review/c' information in my lowercase list.
I want to make all of that strings to lower case
|
2017/10/24
|
[
"https://Stackoverflow.com/questions/46901975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160544/"
] |
if your list *data* like this:
```
data = ['I want to make everything lowercase', '', '']
data = [k.lower() for k in data]
```
if your list *data* is a list of string list:
```
data = [['I want to make everything lowercase'], ['']]
data = [[k.lower()] for l in data for k in l]
```
the fact is that list don't has attribute 'items'
|
You need a list comprehension, not a dict comprehension:
```
lowercase_data = [v.lower() for v in data]
```
|
65,332,466
|
I get a [circular dependency error](https://stackoverflow.com/questions/40705237/django-db-migrations-exceptions-circulardependencyerror) that makes me have to comment out a field. Here is how my models are set up:
```
class Intake(models.Model):
# This field causes a bug on makemigrations. It must be commented when first
# running makemigrations and migrate. Then, uncommented and run makemigrations and
# migrate again.
start_widget = models.ForeignKey(
"widgets.Widget",
on_delete=models.CASCADE,
related_name="start_widget",
null=True,
blank=True,
)
class Widget(PolymorphicModel):
intake = models.ForeignKey(Intake, on_delete=models.CASCADE)
```
By the way, Widget's PolymorphicModel superclass is from [here](https://django-polymorphic.readthedocs.io/en/stable/index.html). Why is this happening and how can I solve it **without having to comment out over and over again**? Thanks!
EDIT: THE FULL ERR:
```
Traceback (most recent call last):
File "/Users/nicksmith/Desktop/proj/backend/manage.py", line 22, in <module>
main()
File "/Users/nicksmith/Desktop/proj/backend/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 282, in build_graph
self.graph.ensure_not_cyclic()
File "/Users/nicksmith/Desktop/proj/backend/venv/lib/python3.9/site-packages/django/db/migrations/graph.py", line 274, in ensure_not_cyclic
raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle))
django.db.migrations.exceptions.CircularDependencyError: intakes.0001_initial, widgets.0001_initial
```
|
2020/12/16
|
[
"https://Stackoverflow.com/questions/65332466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Ok OP let me do this again, you want to find all the rows which are "A" (base condition) and all the rows which are following a "A" row at some point, right ?
Then,
```
is_A = df["ID"] == "A"
not_A_follows_from_A = (df["ID"] != "A") &( df["ID"].shift() == "A")
candidates = df["ID"].loc[is_A | not_A_follows_from_A].unique()
df.loc[df["ID"].isin(candidates)]
```
Should work as intented.
Edit : example
```
df = pd.DataFrame({
'Time': [1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1],
'ID': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'A', 'E', 'E', 'E', 'A', 'F'],
'Val': [7, 2, 7, 5, 1, 6, 7, 3, 2, 4, 7, 8, 2]})
is_A = df["ID"] == "A"
not_A_follows_from_A = (df["ID"] != "A") &( df["ID"].shift() == "A")
candidates = df["ID"].loc[is_A | not_A_follows_from_A].unique()
df.loc[df["ID"].isin(candidates)]
```
outputs this :
```
Time ID Val
0 1 A 7
1 1 A 2
2 1 B 7
3 0 B 5
7 1 A 3
8 0 E 2
9 0 E 4
10 1 E 7
11 1 A 8
12 1 F 2
```
|
Let us try `drop_duplicates`, then `groupby` select the number of unique ID we would like to keep by `head`, and `merge`
```
out = df.merge(df[['Time','ID']].drop_duplicates().groupby('Time').head(2))
Time ID Val
0 1 A 2.0
1 1 A 5.0
2 1 B 2.5
3 1 B 2.0
4 2 A 1.0
5 2 A 6.0
6 2 B 4.0
7 2 B 2.0
```
|
18,451,694
|
e.g. I defined an function which needs several input arguments, if some keyword arguments not being assigned, typically there be an TypeError message, but I want to change it, to output an NaN as the result, could it be done?
```
def myfunc( S0, K ,r....):
if S0 = NaN or .....:
```
How to do it?
Much appreciated.
Edited:
```
def myfunc(a):
return a / 2.5 + 5
print myfunc('whatever')
>python -u "bisectnewton.py"
Traceback (most recent call last):
File "bisectnewton.py", line 6, in <module>
print myfunc('whatever')
File "bisectnewton.py", line 4, in myfunc
return a / 2.5 + 5
TypeError: unsupported operand type(s) for /: 'str' and 'float'
>Exit code: 1
```
What I want is, the myfunc(a) only accpets an number as the input, if some other data type like a string = 'whatever' inputed, I don't want to just output an default error message, I want it to output something like return 'NaN' to tell others that the input should be an number.
Now I changed it to this, but still not working,
btw, is none the same as NaN? I think they're different.
```
def myfunc(S0):
if math.isnan(S0):
return 'NaN'
return a / 2.5 + 5
print myfunc('whatever')
>python -u "bisectnewton.py"
Traceback (most recent call last):
File "bisectnewton.py", line 8, in <module>
print myfunc('whatever')
File "bisectnewton.py", line 4, in myfunc
if math.isnan(S0):
TypeError: a float is required
>Exit code: 1
```
Thanks!
|
2013/08/26
|
[
"https://Stackoverflow.com/questions/18451694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525479/"
] |
You can capture the TypeError and do whatever you want with it:
```
def myfunc(a):
try:
return a / 2.5 + 5
except TypeError:
return float('nan')
print myfunc('whatever')
```
[The Python Tutorial](http://docs.python.org/2/tutorial/errors.html) has an excellent chapter on this subject.
|
```
def myfunc(S0 = None, K = None, r = None, ....):
if S0 is None or K is None or r is None:
return NaN
```
|
18,451,694
|
e.g. I defined an function which needs several input arguments, if some keyword arguments not being assigned, typically there be an TypeError message, but I want to change it, to output an NaN as the result, could it be done?
```
def myfunc( S0, K ,r....):
if S0 = NaN or .....:
```
How to do it?
Much appreciated.
Edited:
```
def myfunc(a):
return a / 2.5 + 5
print myfunc('whatever')
>python -u "bisectnewton.py"
Traceback (most recent call last):
File "bisectnewton.py", line 6, in <module>
print myfunc('whatever')
File "bisectnewton.py", line 4, in myfunc
return a / 2.5 + 5
TypeError: unsupported operand type(s) for /: 'str' and 'float'
>Exit code: 1
```
What I want is, the myfunc(a) only accpets an number as the input, if some other data type like a string = 'whatever' inputed, I don't want to just output an default error message, I want it to output something like return 'NaN' to tell others that the input should be an number.
Now I changed it to this, but still not working,
btw, is none the same as NaN? I think they're different.
```
def myfunc(S0):
if math.isnan(S0):
return 'NaN'
return a / 2.5 + 5
print myfunc('whatever')
>python -u "bisectnewton.py"
Traceback (most recent call last):
File "bisectnewton.py", line 8, in <module>
print myfunc('whatever')
File "bisectnewton.py", line 4, in myfunc
if math.isnan(S0):
TypeError: a float is required
>Exit code: 1
```
Thanks!
|
2013/08/26
|
[
"https://Stackoverflow.com/questions/18451694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525479/"
] |
You can capture the TypeError and do whatever you want with it:
```
def myfunc(a):
try:
return a / 2.5 + 5
except TypeError:
return float('nan')
print myfunc('whatever')
```
[The Python Tutorial](http://docs.python.org/2/tutorial/errors.html) has an excellent chapter on this subject.
|
Yes, to generate a NaN you do `float('nan')`:
```
>>> import math
>> float('nan')
nan
>>> math.isnan(float('nan'))
True
```
So you can `return float('nan')` wherever you want to return the `nan`. I recommend you just raise the exception, though.
|
18,451,694
|
e.g. I defined an function which needs several input arguments, if some keyword arguments not being assigned, typically there be an TypeError message, but I want to change it, to output an NaN as the result, could it be done?
```
def myfunc( S0, K ,r....):
if S0 = NaN or .....:
```
How to do it?
Much appreciated.
Edited:
```
def myfunc(a):
return a / 2.5 + 5
print myfunc('whatever')
>python -u "bisectnewton.py"
Traceback (most recent call last):
File "bisectnewton.py", line 6, in <module>
print myfunc('whatever')
File "bisectnewton.py", line 4, in myfunc
return a / 2.5 + 5
TypeError: unsupported operand type(s) for /: 'str' and 'float'
>Exit code: 1
```
What I want is, the myfunc(a) only accpets an number as the input, if some other data type like a string = 'whatever' inputed, I don't want to just output an default error message, I want it to output something like return 'NaN' to tell others that the input should be an number.
Now I changed it to this, but still not working,
btw, is none the same as NaN? I think they're different.
```
def myfunc(S0):
if math.isnan(S0):
return 'NaN'
return a / 2.5 + 5
print myfunc('whatever')
>python -u "bisectnewton.py"
Traceback (most recent call last):
File "bisectnewton.py", line 8, in <module>
print myfunc('whatever')
File "bisectnewton.py", line 4, in myfunc
if math.isnan(S0):
TypeError: a float is required
>Exit code: 1
```
Thanks!
|
2013/08/26
|
[
"https://Stackoverflow.com/questions/18451694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525479/"
] |
You can capture the TypeError and do whatever you want with it:
```
def myfunc(a):
try:
return a / 2.5 + 5
except TypeError:
return float('nan')
print myfunc('whatever')
```
[The Python Tutorial](http://docs.python.org/2/tutorial/errors.html) has an excellent chapter on this subject.
|
If you don't want to use TypeError, then how about using AttributeError?
```
def myfunc(a):
try:
return a / 2.5 + 5
except AttributeError:
return float('nan')
print myfunc('whatever')
```
|
68,030,577
|
I have obtained 3 lists/arrays in my python script and I am wondering why I am not able to multiply them to values successfully.
```
Array 1: [-0.01896408 -0.0191784 -0.01939271 ... 0.97766441 0.97745009
0.97723578]
Array 2: [ 1.21527999 1.21302709 1.21077419 ... -0.69821075 -0.70046365
-0.70271655]
Array 3: [-0.19631591 -0.1938487 -0.19138148 ... 0.72054634 0.72301355
0.72548077]
```
These are the points I am multiplying it with:
`pointsArray = np.array([[103.890991,1.369125], [103.8892,1.368017], [103.8903,1.367166],[103.890221,1.367944] ])`
What I want to do is this:
```
transformPoint = array1[i]*pointsArray[0] + array2[i]*pointsArray[1] + array3[i]*pointsArray[2]
df["new_X"] = transformPoint[0]
df["new Y"] = transformPoint[1]
```
where the pointsarray value is constant for every iteration in the loop and the arrays should iterate thru all values in them.
This is the error I am getting with the transform point calculation line:
`transformPoint = array1[i]*pointsArray[0] + array2[i]*pointsArray[1] + array3[i]*pointsArray[2]`
```
ValueError: operands could not be broadcast together with shapes (28686,) (2,)
```
How do I fix this or how do I go about with doing this calculation?
Thank you!
|
2021/06/18
|
[
"https://Stackoverflow.com/questions/68030577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233108/"
] |
I can't comment so I have to post my comment like this:
As I understand it you try to multiply elements of the "pointsArray" with a scalar.
Have you tried printing
```
array1[i]
```
to see what it looks like? From the error I would guess that this is somehow not just a number, but the entire array. You could for example try to print
```
array[0][i]
```
to see if the output is the first number in array1.
|
dot is used for matrix multiplication.
Try this:
```
matrix1.dot(matrix2)
```
A bit more clarity:
If you want to use \*, convert both to numpy.matrix and then try.
|
68,030,577
|
I have obtained 3 lists/arrays in my python script and I am wondering why I am not able to multiply them to values successfully.
```
Array 1: [-0.01896408 -0.0191784 -0.01939271 ... 0.97766441 0.97745009
0.97723578]
Array 2: [ 1.21527999 1.21302709 1.21077419 ... -0.69821075 -0.70046365
-0.70271655]
Array 3: [-0.19631591 -0.1938487 -0.19138148 ... 0.72054634 0.72301355
0.72548077]
```
These are the points I am multiplying it with:
`pointsArray = np.array([[103.890991,1.369125], [103.8892,1.368017], [103.8903,1.367166],[103.890221,1.367944] ])`
What I want to do is this:
```
transformPoint = array1[i]*pointsArray[0] + array2[i]*pointsArray[1] + array3[i]*pointsArray[2]
df["new_X"] = transformPoint[0]
df["new Y"] = transformPoint[1]
```
where the pointsarray value is constant for every iteration in the loop and the arrays should iterate thru all values in them.
This is the error I am getting with the transform point calculation line:
`transformPoint = array1[i]*pointsArray[0] + array2[i]*pointsArray[1] + array3[i]*pointsArray[2]`
```
ValueError: operands could not be broadcast together with shapes (28686,) (2,)
```
How do I fix this or how do I go about with doing this calculation?
Thank you!
|
2021/06/18
|
[
"https://Stackoverflow.com/questions/68030577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233108/"
] |
I guess, what you want to do is as follows:
```
import numpy as np
array1 = np.array([-0.01896408, -0.0191784, -0.01939271, 0.97766441, 0.97745009, 0.97723578])
array2 = np.array([ 1.21527999, 1.21302709, 1.21077419, -0.69821075, -0.70046365, -0.70271655])
array3 = np.array([-0.19631591, -0.1938487, -0.19138148, 0.72054634, 0.72301355, 0.72548077])
pointsArray = np.array([[103.890991,1.369125], [103.8892,1.368017], [103.8903,1.367166],[103.890221,1.367944] ])
transformPoint = array1.reshape(-1, 1)*pointsArray[0].reshape(1,-1) + array2.reshape(-1, 1)*pointsArray[1].reshape(1,-1) + array3.reshape(-1, 1)*pointsArray[2].reshape(1,-1)
print(transformPoint)
print(transformPoint.mean(axis=0))
```
The output will be:
```sh
[[103.88895009 1.36816305]
[103.88895138 1.3681607 ]
[103.88895475 1.36815838]
[103.8917436 1.36848707]
[103.89174489 1.36848472]
[103.89174826 1.36848239]]
[103.89034883 1.36832272]
```
Let me know, if this is **NOT** what you wished to achieve, since your question does not explain your objective.
|
dot is used for matrix multiplication.
Try this:
```
matrix1.dot(matrix2)
```
A bit more clarity:
If you want to use \*, convert both to numpy.matrix and then try.
|
68,030,577
|
I have obtained 3 lists/arrays in my python script and I am wondering why I am not able to multiply them to values successfully.
```
Array 1: [-0.01896408 -0.0191784 -0.01939271 ... 0.97766441 0.97745009
0.97723578]
Array 2: [ 1.21527999 1.21302709 1.21077419 ... -0.69821075 -0.70046365
-0.70271655]
Array 3: [-0.19631591 -0.1938487 -0.19138148 ... 0.72054634 0.72301355
0.72548077]
```
These are the points I am multiplying it with:
`pointsArray = np.array([[103.890991,1.369125], [103.8892,1.368017], [103.8903,1.367166],[103.890221,1.367944] ])`
What I want to do is this:
```
transformPoint = array1[i]*pointsArray[0] + array2[i]*pointsArray[1] + array3[i]*pointsArray[2]
df["new_X"] = transformPoint[0]
df["new Y"] = transformPoint[1]
```
where the pointsarray value is constant for every iteration in the loop and the arrays should iterate thru all values in them.
This is the error I am getting with the transform point calculation line:
`transformPoint = array1[i]*pointsArray[0] + array2[i]*pointsArray[1] + array3[i]*pointsArray[2]`
```
ValueError: operands could not be broadcast together with shapes (28686,) (2,)
```
How do I fix this or how do I go about with doing this calculation?
Thank you!
|
2021/06/18
|
[
"https://Stackoverflow.com/questions/68030577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233108/"
] |
I guess, what you want to do is as follows:
```
import numpy as np
array1 = np.array([-0.01896408, -0.0191784, -0.01939271, 0.97766441, 0.97745009, 0.97723578])
array2 = np.array([ 1.21527999, 1.21302709, 1.21077419, -0.69821075, -0.70046365, -0.70271655])
array3 = np.array([-0.19631591, -0.1938487, -0.19138148, 0.72054634, 0.72301355, 0.72548077])
pointsArray = np.array([[103.890991,1.369125], [103.8892,1.368017], [103.8903,1.367166],[103.890221,1.367944] ])
transformPoint = array1.reshape(-1, 1)*pointsArray[0].reshape(1,-1) + array2.reshape(-1, 1)*pointsArray[1].reshape(1,-1) + array3.reshape(-1, 1)*pointsArray[2].reshape(1,-1)
print(transformPoint)
print(transformPoint.mean(axis=0))
```
The output will be:
```sh
[[103.88895009 1.36816305]
[103.88895138 1.3681607 ]
[103.88895475 1.36815838]
[103.8917436 1.36848707]
[103.89174489 1.36848472]
[103.89174826 1.36848239]]
[103.89034883 1.36832272]
```
Let me know, if this is **NOT** what you wished to achieve, since your question does not explain your objective.
|
I can't comment so I have to post my comment like this:
As I understand it you try to multiply elements of the "pointsArray" with a scalar.
Have you tried printing
```
array1[i]
```
to see what it looks like? From the error I would guess that this is somehow not just a number, but the entire array. You could for example try to print
```
array[0][i]
```
to see if the output is the first number in array1.
|
57,487,274
|
I have a below API response. This is a very small subset which I am pasting here for reference. there can be 80+ columns on this.
```
[["name","age","children","city", "info"], ["Richard Walter", "35", ["Simon", "Grace"], {"mobile":"yes","house_owner":"no"}],
["Mary", "43", ["Phil", "Marshall", "Emily"], {"mobile":"yes","house_owner":"yes", "own_stocks": "yes"}],
["Drew", "21", [], {"mobile":"yes","house_owner":"no", "investor":"yes"}]]
```
Initially I thought pandas could help here and searched accordingly but as a newbie to python/coding I was not able to get much out of it. any help or guidance is appreciated.
I am expecting output in a JSON key-value pair format such as below.
```
{"name":"Mary", "age":"43", "children":["Phil", "Marshall", "Emily"],"info_mobile":"yes","info_house_owner":"yes", "info_own_stocks": "yes"},
{"name":"Drew", "age":"21", "children":[], "info_mobile":"yes","info_house_owner":"no", "info_investor":"yes"}]```
```
|
2019/08/14
|
[
"https://Stackoverflow.com/questions/57487274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924956/"
] |
There are times when using Python seems to be very effective, this might be one of those.
```
df['scores'].apply(lambda x: sum(float(i) if len(x) > 0 else np.nan for i in x.split(',')))
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
```
|
You can just do `str.split`
```
df.scores.str.split(',',expand=True).astype(float).sum(1).mask(df.scores.isnull())
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
dtype: float64
```
|
57,487,274
|
I have a below API response. This is a very small subset which I am pasting here for reference. there can be 80+ columns on this.
```
[["name","age","children","city", "info"], ["Richard Walter", "35", ["Simon", "Grace"], {"mobile":"yes","house_owner":"no"}],
["Mary", "43", ["Phil", "Marshall", "Emily"], {"mobile":"yes","house_owner":"yes", "own_stocks": "yes"}],
["Drew", "21", [], {"mobile":"yes","house_owner":"no", "investor":"yes"}]]
```
Initially I thought pandas could help here and searched accordingly but as a newbie to python/coding I was not able to get much out of it. any help or guidance is appreciated.
I am expecting output in a JSON key-value pair format such as below.
```
{"name":"Mary", "age":"43", "children":["Phil", "Marshall", "Emily"],"info_mobile":"yes","info_house_owner":"yes", "info_own_stocks": "yes"},
{"name":"Drew", "age":"21", "children":[], "info_mobile":"yes","info_house_owner":"no", "info_investor":"yes"}]```
```
|
2019/08/14
|
[
"https://Stackoverflow.com/questions/57487274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924956/"
] |
You can just do `str.split`
```
df.scores.str.split(',',expand=True).astype(float).sum(1).mask(df.scores.isnull())
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
dtype: float64
```
|
Another solution using explode, groupby and sum functions:
```
df.scores.str.split(',').explode().astype(float).groupby(level=0).sum(min_count=1)
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
Name: scores, dtype: float64
```
Or to make @WeNYoBen's answer slightly shorter":
```
df.scores.str.split(',',expand=True).astype(float).sum(1, min_count=1)
```
|
57,487,274
|
I have a below API response. This is a very small subset which I am pasting here for reference. there can be 80+ columns on this.
```
[["name","age","children","city", "info"], ["Richard Walter", "35", ["Simon", "Grace"], {"mobile":"yes","house_owner":"no"}],
["Mary", "43", ["Phil", "Marshall", "Emily"], {"mobile":"yes","house_owner":"yes", "own_stocks": "yes"}],
["Drew", "21", [], {"mobile":"yes","house_owner":"no", "investor":"yes"}]]
```
Initially I thought pandas could help here and searched accordingly but as a newbie to python/coding I was not able to get much out of it. any help or guidance is appreciated.
I am expecting output in a JSON key-value pair format such as below.
```
{"name":"Mary", "age":"43", "children":["Phil", "Marshall", "Emily"],"info_mobile":"yes","info_house_owner":"yes", "info_own_stocks": "yes"},
{"name":"Drew", "age":"21", "children":[], "info_mobile":"yes","info_house_owner":"no", "info_investor":"yes"}]```
```
|
2019/08/14
|
[
"https://Stackoverflow.com/questions/57487274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924956/"
] |
There are times when using Python seems to be very effective, this might be one of those.
```
df['scores'].apply(lambda x: sum(float(i) if len(x) > 0 else np.nan for i in x.split(',')))
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
```
|
Another solution using explode, groupby and sum functions:
```
df.scores.str.split(',').explode().astype(float).groupby(level=0).sum(min_count=1)
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
Name: scores, dtype: float64
```
Or to make @WeNYoBen's answer slightly shorter":
```
df.scores.str.split(',',expand=True).astype(float).sum(1, min_count=1)
```
|
48,176,802
|
I'm very new to work with `xlsxwriter` in python. I have created a scraper in python and it is working flawlessly. However, when I try to write these data in an excel file using `xlsxwriter` I get stuck. What I have written so far can create an excel file and write the last populated data derived from the for loop. How can I rectify my script to write all the data rather than the last one. It would be better If i knew how to append the newly populated values on the fly.
The bottom line is, I'm getting two issues:
1. My script writes only the last populated values
2. The two fields are being written in a line, as in `row("A1"), row("A2")` but I wish to have them like `row("A1"), row("B1")` and so on.
Script I've tried with:
```
import requests
from bs4 import BeautifulSoup
import xlsxwriter
row = 0
col = 0
with xlsxwriter.Workbook('torrent.xlsx') as workbook:
worksheet = workbook.add_worksheet()
with requests.Session() as s:
s.headers = {"User-Agent":"Mozilla/5.0"}
res = s.get("https://www.yify-torrent.org/search/1080p/")
soup = BeautifulSoup(res.text, 'lxml')
for item in soup.select(".mv"):
name = item.select("a")[0].text
link = item.select("a")[0]['href']
data = name , link
for elem in data:
worksheet.write(row, col, elem)
row += 1
```
The result I'm having like (in a line):
```
title
link
```
Whereas, I wish to have them like (in separate rows):
```
title link
title1 link1
title2 link2
```
and so on.
|
2018/01/09
|
[
"https://Stackoverflow.com/questions/48176802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] |
1. Each time through the first `for` loop, you overwrite `data`, so only the last thing assigned survives. This could be addressed by moving your second `for` loop to be inside the first, so it gets called for each value of `data`.
2. If you want things to be in different columns, you need to use different values for `col` when you call `worksheet.write`. You use `row += 1` to advance to subsequent rows; `col += 1` would do the same for columns.
|
As Scott Hunter noted, your overwriting your data, which is stored just fine as a tuple in your data variable. However, it seems like your issue is in your for loop, where you're only adding to row within each block, which explains why your code is traveling only vertically in your spread sheet. Perhaps rearranging things and adding in an iterator could help?
```
for idx,elem in enumerate(data):
worksheet.write(row, idx, elem)
row += 1
```
Enumerate function will consistently add 1 to the idx variable for every iteration of code, therefor this single block of code can extend as far out as your tuple of data is long.
Hope this helps!
|
61,715,377
|
So I have a docker project, which is some kind of Python pytest that runs subprocess on an executable file as a blackbox test. I would like to build the container, and then run it each time by copying the executable file to a dedicated folder inside the container WORKDIR (e.g. exec/). But I am not sure how to do it.
Currently, I have to first include the executable in the folder then build the container.
The structure is currently like this:
```
my_test_repo
| |-- exec
| | |-- my_executable
| |-- tests
| | |-- test_the_executable.py
| |-- Dockerfile
```
I skipped over some other such as setup.
In the Dockerfile, I do the following:
```
FROM python:3.7.7-buster
WORKDIR /app
COPY . /app
RUN pip install --trusted-host pypi.python.org .
RUN pip install pytest
ENV NAME "Docker"
RUN pytest ./tests/ --executable=./exec/my_executable
```
For the last time, I setup a pytest fixture to accept the path of the executable.
I can run the test by building it:
```
docker build --tag testproject:1.0 .
```
How can I edit it so that the containers only consists of all the tests file. And it interacts with users so that I can `cp` my executable from my local dir to the container then run the test?
Many thanks.
|
2020/05/10
|
[
"https://Stackoverflow.com/questions/61715377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4930109/"
] |
'Week' in mysql has 2 inputs: date and week type. By default it's equal 0. That means week starts from sunday. Try this code:
```
SELECT IFNULL(SUM(rendeles_dbszam),0) as eladott_pizzak_szama FROM rendeles WHERE WEEK(rendeles_idopont) = WEEK(CURRENT_DATE(),1)
```
|
You can use this little formula to get the Monday starting the week of any given DATE, DATETIME, or TIMESTAMP object.
```
FROM_DAYS(TO_DAYS(datestamp) -MOD(TO_DAYS(datestamp) -2, 7))
```
I like to use it in a stored function named `TRUNC_MONDAY(datestamp)` defined like this.
```
DELIMITER $$
DROP FUNCTION IF EXISTS TRUNC_MONDAY$$
CREATE
FUNCTION TRUNC_MONDAY(datestamp DATETIME)
RETURNS DATE DETERMINISTIC NO SQL
COMMENT 'preceding Monday'
RETURN FROM_DAYS(TO_DAYS(datestamp) -MOD(TO_DAYS(datestamp) -2, 7))$$
DELIMITER ;
```
Then you can do stuff like this
```
SELECT IFNULL(SUM(rendeles_dbszam),0) as eladott_pizzak_szama
FROM rendeles
WHERE TRUNC_MONDAY(rendeles_idopont) = TRUNC_MONDAY(CURRENT_DATE())
```
or even this to get a report covering eight previous weeks and the current week.
```
SELECT SUM(rendeles_dbszam) as eladott_pizzak_szama,
TRUNC_MONDAY(rendeles_idopont) as week_beginning
FROM rendeles
WHERE rendeles_idopont >= TRUNC_MONDAY(CURDATE()) - INTERVAL 8 WEEK
AND rendeles_idopoint < TRUNC_MONDAY(CURDATE()) + INTERVAL 1 WEEK
GROUP BY TRUNC_MONDAY(rendeles_idopont)
```
I particularly like this `TRUNC_MONDAY()` approach because it works unambiguously even for calendar weeks that contain New Years' Days.
(If you want `TRUNC_SUNDAY()` change the `-2` in the formula to `-1`.)
|
40,920,564
|
I am using two different `HTTP POST` utilities ([poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) out of Firefox as well as `Python` [requests](http://docs.python-requests.org/en/master/) API) to post a simple `SPARQL` insert to `Virtuoso`.
My URL is: `http://localhost:8890/sparql`
My request parameters are:
```
default-graph-uri: <MY_GRAPH>
should-sponge: soft
debug: on
timeout:
format: application/xml
save: display
fname:
```
I put the actual SPARQL (`INSERT DATA { GRAPH...`) in the content of the message.
I tried different content types, none of which worked. I do get 200 but the response is in HTML even though the above parameter set specifies `application/xml`, however, no data is inserted. When I try content type of `text/turtle`, I get 409 Invalid Path, which is also referenced in [this post](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html).
I can successfully do `HTTP GET`, however, that has a payload length limitation which I would like to exceed for performance reasons. The only difference with the GET is that the SPARQL goes in the URL under `query` parameter and the POST **should** enable a much larger payload in the message content, by including multiple triples in the same request, not just one (I have 100s of 1000s of inserts). I was trying to follow [this documentation page](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedprotocolendpointurisparqlauthex).
|
2016/12/01
|
[
"https://Stackoverflow.com/questions/40920564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312080/"
] |
I stopped by this question days ago trying to achieve the same with `curl`. Since it is a powerful (and far more convenient) alternative to browser extensions, here is the formulation that eventually proved successful:
```
curl -X POST \
-H "Content-Type:application/sparql-update" \
-H "Accept:text/html" \
--data "select distinct ?Concept where {[] a ?Concept} LIMIT 100" http://localhost:8890/sparql
```
More details on the headers in [this thread](https://sourceforge.net/p/virtuoso/mailman/virtuoso-users/thread/KfF_dXPTTyjakF6oWNlzWHOAXbCxkZ4h1erB4PSxdbCe8seqxaDqGq0vyg0VyIg3j-QoooTagDhE0R660W_udXI9wEsYVGsRE463O8k3jhk%3D%40protonmail.ch/#msg37272403).
|
There are many aspects to this "question" making it difficult to provide a simple answer, suitable to this site. This is one of the reasons I suggested the mailing list, which is better suited to conversational and/or multi-facet assistance.
* Have you tried using `curl` as most of our examples do?
* Looking at the [Poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) page on Mozilla Add-Ons, I see that you may need to manually add a `?` to the end of your target URI -- so `http://localhost:8890/sparql?` rather than `http://localhost:8890/sparql` -- and it's not clear whether you've done that in your testing. On the [project page](https://code.google.com/archive/p/poster-extension/), I also note its [last commit](https://code.google.com/archive/p/poster-extension/source/default/commits) was in 2012, and there are [a great many open issues](https://code.google.com/archive/p/poster-extension/issues).
* I'm not at all familiar with Python, so I've not dug in there.
* Have you tried setting an `Accept:` header? This can have significant impact on the content returned by the server.
* If I understand your described efforts correctly, your `format:` query parameter should be `output-format:`, and its value should not be `application/xml` but one of the supported formats [listed in the documentation](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedmimesofprotocolserver).
* Neither the [`virtuoso-users` post you referenced](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html) nor this question have enough detail to analyze the cause of the `409 Invalid Path` error. Explicit details that allow us to reproduce this result would be helpful, optimally in a distinct thread.
|
40,920,564
|
I am using two different `HTTP POST` utilities ([poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) out of Firefox as well as `Python` [requests](http://docs.python-requests.org/en/master/) API) to post a simple `SPARQL` insert to `Virtuoso`.
My URL is: `http://localhost:8890/sparql`
My request parameters are:
```
default-graph-uri: <MY_GRAPH>
should-sponge: soft
debug: on
timeout:
format: application/xml
save: display
fname:
```
I put the actual SPARQL (`INSERT DATA { GRAPH...`) in the content of the message.
I tried different content types, none of which worked. I do get 200 but the response is in HTML even though the above parameter set specifies `application/xml`, however, no data is inserted. When I try content type of `text/turtle`, I get 409 Invalid Path, which is also referenced in [this post](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html).
I can successfully do `HTTP GET`, however, that has a payload length limitation which I would like to exceed for performance reasons. The only difference with the GET is that the SPARQL goes in the URL under `query` parameter and the POST **should** enable a much larger payload in the message content, by including multiple triples in the same request, not just one (I have 100s of 1000s of inserts). I was trying to follow [this documentation page](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedprotocolendpointurisparqlauthex).
|
2016/12/01
|
[
"https://Stackoverflow.com/questions/40920564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312080/"
] |
If you are using python, I would avoid using the `requests` library. There are some dedicated libraries for RDF which abstract the process and make your life easier.
Try:
* [SPARQLWrapper](https://sparqlwrapper.readthedocs.io/en/latest/#)
* [RDFLib](https://rdflib.readthedocs.io/en/stable/#)
[They are both form the same family of packages from rdflib](https://rdflib.dev/)
Based on experience, I find the SPARQLWrapper significantly simpler and easier to use for your use case. It's an abstracted version of RDFLib. The docs suggest something like this could work:
```
from SPARQLWrapper import SPARQLWrapper, POST
sparql = SPARQLWrapper("https://example.org/sparql")
sparql.setCredentials("some-login", "some-password") # if required
sparql.setMethod(POST) # this is the crucial option
sparql.setQuery("""
<QUERY GOES HERE>
""".format(PARSE SOME VARS INTO THE QUERY HERE IF YOU WANT)
)
results = sparql.query()
print results.response.read()
```
Make sure you add the option for POST. You should be doing bulk I/O in no time :).
|
There are many aspects to this "question" making it difficult to provide a simple answer, suitable to this site. This is one of the reasons I suggested the mailing list, which is better suited to conversational and/or multi-facet assistance.
* Have you tried using `curl` as most of our examples do?
* Looking at the [Poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) page on Mozilla Add-Ons, I see that you may need to manually add a `?` to the end of your target URI -- so `http://localhost:8890/sparql?` rather than `http://localhost:8890/sparql` -- and it's not clear whether you've done that in your testing. On the [project page](https://code.google.com/archive/p/poster-extension/), I also note its [last commit](https://code.google.com/archive/p/poster-extension/source/default/commits) was in 2012, and there are [a great many open issues](https://code.google.com/archive/p/poster-extension/issues).
* I'm not at all familiar with Python, so I've not dug in there.
* Have you tried setting an `Accept:` header? This can have significant impact on the content returned by the server.
* If I understand your described efforts correctly, your `format:` query parameter should be `output-format:`, and its value should not be `application/xml` but one of the supported formats [listed in the documentation](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedmimesofprotocolserver).
* Neither the [`virtuoso-users` post you referenced](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html) nor this question have enough detail to analyze the cause of the `409 Invalid Path` error. Explicit details that allow us to reproduce this result would be helpful, optimally in a distinct thread.
|
40,920,564
|
I am using two different `HTTP POST` utilities ([poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) out of Firefox as well as `Python` [requests](http://docs.python-requests.org/en/master/) API) to post a simple `SPARQL` insert to `Virtuoso`.
My URL is: `http://localhost:8890/sparql`
My request parameters are:
```
default-graph-uri: <MY_GRAPH>
should-sponge: soft
debug: on
timeout:
format: application/xml
save: display
fname:
```
I put the actual SPARQL (`INSERT DATA { GRAPH...`) in the content of the message.
I tried different content types, none of which worked. I do get 200 but the response is in HTML even though the above parameter set specifies `application/xml`, however, no data is inserted. When I try content type of `text/turtle`, I get 409 Invalid Path, which is also referenced in [this post](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html).
I can successfully do `HTTP GET`, however, that has a payload length limitation which I would like to exceed for performance reasons. The only difference with the GET is that the SPARQL goes in the URL under `query` parameter and the POST **should** enable a much larger payload in the message content, by including multiple triples in the same request, not just one (I have 100s of 1000s of inserts). I was trying to follow [this documentation page](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedprotocolendpointurisparqlauthex).
|
2016/12/01
|
[
"https://Stackoverflow.com/questions/40920564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312080/"
] |
I stopped by this question days ago trying to achieve the same with `curl`. Since it is a powerful (and far more convenient) alternative to browser extensions, here is the formulation that eventually proved successful:
```
curl -X POST \
-H "Content-Type:application/sparql-update" \
-H "Accept:text/html" \
--data "select distinct ?Concept where {[] a ?Concept} LIMIT 100" http://localhost:8890/sparql
```
More details on the headers in [this thread](https://sourceforge.net/p/virtuoso/mailman/virtuoso-users/thread/KfF_dXPTTyjakF6oWNlzWHOAXbCxkZ4h1erB4PSxdbCe8seqxaDqGq0vyg0VyIg3j-QoooTagDhE0R660W_udXI9wEsYVGsRE463O8k3jhk%3D%40protonmail.ch/#msg37272403).
|
This seems to be a Virtuoso specific issue. You can only post a query by using content type "application/sparql-update" instead of "application/sparql-query" which is common.
The request is done as follows with Python:
```
headers = {
'Content-Type': 'application/sparql-update',
'Accept': 'application/json'
}
s = Session();
s.mount(server_url, HTTPAdapter(max_retries=1))
response: Response = s.post(server_url, data=<sparql_string>, headers=headers, timeout=100)
return response.json();
```
|
40,920,564
|
I am using two different `HTTP POST` utilities ([poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) out of Firefox as well as `Python` [requests](http://docs.python-requests.org/en/master/) API) to post a simple `SPARQL` insert to `Virtuoso`.
My URL is: `http://localhost:8890/sparql`
My request parameters are:
```
default-graph-uri: <MY_GRAPH>
should-sponge: soft
debug: on
timeout:
format: application/xml
save: display
fname:
```
I put the actual SPARQL (`INSERT DATA { GRAPH...`) in the content of the message.
I tried different content types, none of which worked. I do get 200 but the response is in HTML even though the above parameter set specifies `application/xml`, however, no data is inserted. When I try content type of `text/turtle`, I get 409 Invalid Path, which is also referenced in [this post](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html).
I can successfully do `HTTP GET`, however, that has a payload length limitation which I would like to exceed for performance reasons. The only difference with the GET is that the SPARQL goes in the URL under `query` parameter and the POST **should** enable a much larger payload in the message content, by including multiple triples in the same request, not just one (I have 100s of 1000s of inserts). I was trying to follow [this documentation page](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedprotocolendpointurisparqlauthex).
|
2016/12/01
|
[
"https://Stackoverflow.com/questions/40920564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312080/"
] |
I stopped by this question days ago trying to achieve the same with `curl`. Since it is a powerful (and far more convenient) alternative to browser extensions, here is the formulation that eventually proved successful:
```
curl -X POST \
-H "Content-Type:application/sparql-update" \
-H "Accept:text/html" \
--data "select distinct ?Concept where {[] a ?Concept} LIMIT 100" http://localhost:8890/sparql
```
More details on the headers in [this thread](https://sourceforge.net/p/virtuoso/mailman/virtuoso-users/thread/KfF_dXPTTyjakF6oWNlzWHOAXbCxkZ4h1erB4PSxdbCe8seqxaDqGq0vyg0VyIg3j-QoooTagDhE0R660W_udXI9wEsYVGsRE463O8k3jhk%3D%40protonmail.ch/#msg37272403).
|
If you are using python, I would avoid using the `requests` library. There are some dedicated libraries for RDF which abstract the process and make your life easier.
Try:
* [SPARQLWrapper](https://sparqlwrapper.readthedocs.io/en/latest/#)
* [RDFLib](https://rdflib.readthedocs.io/en/stable/#)
[They are both form the same family of packages from rdflib](https://rdflib.dev/)
Based on experience, I find the SPARQLWrapper significantly simpler and easier to use for your use case. It's an abstracted version of RDFLib. The docs suggest something like this could work:
```
from SPARQLWrapper import SPARQLWrapper, POST
sparql = SPARQLWrapper("https://example.org/sparql")
sparql.setCredentials("some-login", "some-password") # if required
sparql.setMethod(POST) # this is the crucial option
sparql.setQuery("""
<QUERY GOES HERE>
""".format(PARSE SOME VARS INTO THE QUERY HERE IF YOU WANT)
)
results = sparql.query()
print results.response.read()
```
Make sure you add the option for POST. You should be doing bulk I/O in no time :).
|
40,920,564
|
I am using two different `HTTP POST` utilities ([poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) out of Firefox as well as `Python` [requests](http://docs.python-requests.org/en/master/) API) to post a simple `SPARQL` insert to `Virtuoso`.
My URL is: `http://localhost:8890/sparql`
My request parameters are:
```
default-graph-uri: <MY_GRAPH>
should-sponge: soft
debug: on
timeout:
format: application/xml
save: display
fname:
```
I put the actual SPARQL (`INSERT DATA { GRAPH...`) in the content of the message.
I tried different content types, none of which worked. I do get 200 but the response is in HTML even though the above parameter set specifies `application/xml`, however, no data is inserted. When I try content type of `text/turtle`, I get 409 Invalid Path, which is also referenced in [this post](https://www.mail-archive.com/virtuoso-users@lists.sourceforge.net/msg07015.html).
I can successfully do `HTTP GET`, however, that has a payload length limitation which I would like to exceed for performance reasons. The only difference with the GET is that the SPARQL goes in the URL under `query` parameter and the POST **should** enable a much larger payload in the message content, by including multiple triples in the same request, not just one (I have 100s of 1000s of inserts). I was trying to follow [this documentation page](http://docs.openlinksw.com/virtuoso/rdfsparqlprotocolendpoint/#rdfsupportedprotocolendpointurisparqlauthex).
|
2016/12/01
|
[
"https://Stackoverflow.com/questions/40920564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312080/"
] |
If you are using python, I would avoid using the `requests` library. There are some dedicated libraries for RDF which abstract the process and make your life easier.
Try:
* [SPARQLWrapper](https://sparqlwrapper.readthedocs.io/en/latest/#)
* [RDFLib](https://rdflib.readthedocs.io/en/stable/#)
[They are both form the same family of packages from rdflib](https://rdflib.dev/)
Based on experience, I find the SPARQLWrapper significantly simpler and easier to use for your use case. It's an abstracted version of RDFLib. The docs suggest something like this could work:
```
from SPARQLWrapper import SPARQLWrapper, POST
sparql = SPARQLWrapper("https://example.org/sparql")
sparql.setCredentials("some-login", "some-password") # if required
sparql.setMethod(POST) # this is the crucial option
sparql.setQuery("""
<QUERY GOES HERE>
""".format(PARSE SOME VARS INTO THE QUERY HERE IF YOU WANT)
)
results = sparql.query()
print results.response.read()
```
Make sure you add the option for POST. You should be doing bulk I/O in no time :).
|
This seems to be a Virtuoso specific issue. You can only post a query by using content type "application/sparql-update" instead of "application/sparql-query" which is common.
The request is done as follows with Python:
```
headers = {
'Content-Type': 'application/sparql-update',
'Accept': 'application/json'
}
s = Session();
s.mount(server_url, HTTPAdapter(max_retries=1))
response: Response = s.post(server_url, data=<sparql_string>, headers=headers, timeout=100)
return response.json();
```
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
Another symptom of this problem for me was if I went into the python console of my virtualenv and did `import ssl` it would error out. Turns out my virtualenv wasn't using the `brew` version of python, just the default install on my machine. No clue why the default install suddenly stopped working, but here's how I fixed it the problem:
* `rmvirtualenv myvirtualenv`
* `brew update`
* `brew reinstall python`
* `mkvirtualenv -p /usr/local/Cellar/python/whatever_version_number/bin/python myvirtualenv`
|
In many cases this is caused by an out of date virtualenv, here's a script to regenerate your virtualenv(s): <https://gist.github.com/WoLpH/fb98f7dc6ba6f05da2b8>
Simply copy it to a file (downloadable link above) and execute it like this: `zsh -e recreate_virtualenvs.sh <project_name>`
```
#!/bin/zsh -e
if [ ! -d "$PROJECT_HOME" ]; then
echo 'Your $PROJECT_HOME needs to be defined'
echo 'http://virtualenvwrapper.readthedocs.org/en/latest/install.html#location-of-project-directories'
exit 1
fi
if [ "" = "$1" ]; then
echo "Usage: $0 <project_name>"
exit 1
fi
env="$1"
project_dir="$PROJECT_HOME/$1"
env_dir="$HOME/envs/$1"
function command_exists(){
type $1 2>/dev/null | grep -vq ' not found'
}
if command_exists workon; then
echo 'Getting virtualenvwrapper from environment'
# Workon exists, nothing to do :)
elif [ -x ~/bin/mount_workon ]; then
echo 'Using mount workon'
# Optional support for packaged project directories and virtualenvs using
# https://github.com/WoLpH/dotfiles/blob/master/bin/mount_workon
. ~/bin/mount_workon
mount_file "$project_dir"
mount_file "$env_dir"
elif command_exists virtualenvwrapper.sh; then
echo 'Using virtualenvwrapper'
. $(which virtualenvwrapper.sh)
fi
if ! command_exists workon; then
echo 'Virtualenvwrapper not found, please install it'
exit 1
fi
rmvirtualenv $env || true
echo "Recreating $env"
mkvirtualenv $env || true
workon "$env" || true
pip install virtualenv{,wrapper}
cd $project_dir
setvirtualenvproject
if [ -f setup.py ]; then
echo "Installing local package"
pip install -e .
fi
function install_requirements(){
# Installing requirements from given file, if it exists
if [ -f "$1" ]; then
echo "Installing requirements from $1"
pip install -r "$1"
fi
}
install_requirements requirements_test.txt
install_requirements requirements-test.txt
install_requirements requirements.txt
install_requirements test_requirements.txt
install_requirements test-requirements.txt
if [ -d docs ]; then
echo "Found docs, installing sphinx"
pip install sphinx{,-pypi-upload} py
fi
echo "Installing ipython"
pip install ipython
if [ -f tox.ini ]; then
deps=$(python -c "
parser=__import__('ConfigParser').ConfigParser();
parser.read('tox.ini');
print parser.get('testenv', 'deps').strip().replace('{toxinidir}/', '')")
echo "Found deps from tox.ini: $deps"
echo $deps | parallel -v --no-notice pip install {}
fi
if [ -f .travis.yml ]; then
echo "Found deps from travis:"
installs=$(grep 'pip install' .travis.yml | grep -v '\$' | sed -e 's/.*pip install/pip install/' | grep -v 'pip install . --use-mirrors' | sed -e 's/$/;/')
echo $installs
eval $installs
fi
deactivate
```
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
I'm using Redhat and have met the same problem.
My solution is :
1. install openssl and openssl-devel ---- yum install openssl openssl-devel -y
2. install krb5-devel ---- yum install krb5-devel
3. change to your python's directory and recompile it ---- make
If I didn't do the 2nd step, when I recompiled my python2.7 , the log would say " fail to build module \_ssl".
|
For Ubuntu
==========
First check wheather install openssl-develop
```
sudo apt-get install libssl-dev
```
Try another way to reinstall `pip`
```
sudo apt-get install python-setuptools
sudo easy_install pip
```
use `setuptools` to install pip rather than install with source code may can solve the problem of dependency.
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
I was having this problem on Mac OSX, even after confirming my PATH, etc.
Did a; pip uninstall virtualenv then install virtualenv and it seemed to works now.
At the time I had forced brew to link openssl, unlinked it and virtualenv still seems to work but maybe that's because it was originally linked when I reinstalled it.
|
In many cases this is caused by an out of date virtualenv, here's a script to regenerate your virtualenv(s): <https://gist.github.com/WoLpH/fb98f7dc6ba6f05da2b8>
Simply copy it to a file (downloadable link above) and execute it like this: `zsh -e recreate_virtualenvs.sh <project_name>`
```
#!/bin/zsh -e
if [ ! -d "$PROJECT_HOME" ]; then
echo 'Your $PROJECT_HOME needs to be defined'
echo 'http://virtualenvwrapper.readthedocs.org/en/latest/install.html#location-of-project-directories'
exit 1
fi
if [ "" = "$1" ]; then
echo "Usage: $0 <project_name>"
exit 1
fi
env="$1"
project_dir="$PROJECT_HOME/$1"
env_dir="$HOME/envs/$1"
function command_exists(){
type $1 2>/dev/null | grep -vq ' not found'
}
if command_exists workon; then
echo 'Getting virtualenvwrapper from environment'
# Workon exists, nothing to do :)
elif [ -x ~/bin/mount_workon ]; then
echo 'Using mount workon'
# Optional support for packaged project directories and virtualenvs using
# https://github.com/WoLpH/dotfiles/blob/master/bin/mount_workon
. ~/bin/mount_workon
mount_file "$project_dir"
mount_file "$env_dir"
elif command_exists virtualenvwrapper.sh; then
echo 'Using virtualenvwrapper'
. $(which virtualenvwrapper.sh)
fi
if ! command_exists workon; then
echo 'Virtualenvwrapper not found, please install it'
exit 1
fi
rmvirtualenv $env || true
echo "Recreating $env"
mkvirtualenv $env || true
workon "$env" || true
pip install virtualenv{,wrapper}
cd $project_dir
setvirtualenvproject
if [ -f setup.py ]; then
echo "Installing local package"
pip install -e .
fi
function install_requirements(){
# Installing requirements from given file, if it exists
if [ -f "$1" ]; then
echo "Installing requirements from $1"
pip install -r "$1"
fi
}
install_requirements requirements_test.txt
install_requirements requirements-test.txt
install_requirements requirements.txt
install_requirements test_requirements.txt
install_requirements test-requirements.txt
if [ -d docs ]; then
echo "Found docs, installing sphinx"
pip install sphinx{,-pypi-upload} py
fi
echo "Installing ipython"
pip install ipython
if [ -f tox.ini ]; then
deps=$(python -c "
parser=__import__('ConfigParser').ConfigParser();
parser.read('tox.ini');
print parser.get('testenv', 'deps').strip().replace('{toxinidir}/', '')")
echo "Found deps from tox.ini: $deps"
echo $deps | parallel -v --no-notice pip install {}
fi
if [ -f .travis.yml ]; then
echo "Found deps from travis:"
installs=$(grep 'pip install' .travis.yml | grep -v '\$' | sed -e 's/.*pip install/pip install/' | grep -v 'pip install . --use-mirrors' | sed -e 's/$/;/')
echo $installs
eval $installs
fi
deactivate
```
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
You need to install the OpenSSL header files before building Python if you need SSL support. On Debian and Ubuntu, they are in a package called `libssl-dev`. You might need some more dependencies, [as noted here](https://askubuntu.com/questions/101591/how-do-i-install-python-2-7-2-on-ubuntu).
|
For Ubuntu
==========
First check wheather install openssl-develop
```
sudo apt-get install libssl-dev
```
Try another way to reinstall `pip`
```
sudo apt-get install python-setuptools
sudo easy_install pip
```
use `setuptools` to install pip rather than install with source code may can solve the problem of dependency.
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
OSX + homebrew users:
=====================
You can get the latest updates to the recipe:
```
brew reinstall python
```
But if you still get the issue, e.g. maybe you have upgraded your OS, then you may need to get the latest openssl first. You can check which version and where it is used from:
```
openssl version -a
which openssl
```
To get the latest openssl:
```
brew update
brew install openssl
brew link --overwrite --dry-run openssl # safety first.
brew link openssl --overwrite
```
This may issue a warning:
```
bash-4.3$ brew link --overwrite --dry-run openssl
Warning: Refusing to link: openssl Linking keg-only openssl means you may end up linking against the insecure, deprecated system OpenSSL while using the headers from Homebrew's openssl.
Instead, pass the full include/library paths to your compiler e.g.:
-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib
```
Side note: this warning means that for other apps, you may want to use
```
export LDFLAGS=-L/usr/local/opt/openssl/lib
export CPPFLAGS=-I/usr/local/opt/openssl/include
```
Then recompile python:
```
brew uninstall python
brew install python --with-brewed-openssl
```
or for python 3
```
brew uninstall python3
brew install python3 --with-brewed-openssl
```
|
Another symptom of this problem for me was if I went into the python console of my virtualenv and did `import ssl` it would error out. Turns out my virtualenv wasn't using the `brew` version of python, just the default install on my machine. No clue why the default install suddenly stopped working, but here's how I fixed it the problem:
* `rmvirtualenv myvirtualenv`
* `brew update`
* `brew reinstall python`
* `mkvirtualenv -p /usr/local/Cellar/python/whatever_version_number/bin/python myvirtualenv`
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
You need to install OpenSSl before make and install Python to solve the problem.
On Centos:
```
yum install openssl openssl-devel -y
```
[source](http://www.leonli.co.uk/blog/723/solve-python-importerror-cannot-import-name-httpshandler)
|
On OSX, brew kept refusing to link against its openssl with this error:
```
15:27 $ brew link --force openssl
Warning: Refusing to link: openssl
Linking keg-only openssl means you may end up linking against the insecure,
deprecated system OpenSSL while using the headers from Homebrew's openssl.
Instead, pass the full include/library paths to your compiler e.g.:
-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib
```
I finally was able to get it working with:
```
brew remove openssl
brew uninstall --force openssl
brew install openssl
export LDFLAGS=-L/usr/local/opt/openssl/lib
export CPPFLAGS=-I/usr/local/opt/openssl/include
brew remove python
brew update
brew install python
```
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
I was having this problem on Mac OSX, even after confirming my PATH, etc.
Did a; pip uninstall virtualenv then install virtualenv and it seemed to works now.
At the time I had forced brew to link openssl, unlinked it and virtualenv still seems to work but maybe that's because it was originally linked when I reinstalled it.
|
It seems your `pip` requires `HTTPSHandler` which is part of `SSL` library.
**OSX**
On OS X you should link OpenSSL during Python installation (See: [#14497](https://github.com/Homebrew/homebrew/issues/14497)).
For Python 2:
```
brew reinstall python --with-brewed-openssl
pip install --upgrade pip
```
For Python 3:
```
brew reinstall python3 --with-brewed-openssl
pip3 install --upgrade pip
```
You could have multiple Python instances together, to list them run:
```
brew list | grep ^python
```
Or list your version via `ls -al /usr/local/lib/python*`.
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
I was having this problem on Mac OSX, even after confirming my PATH, etc.
Did a; pip uninstall virtualenv then install virtualenv and it seemed to works now.
At the time I had forced brew to link openssl, unlinked it and virtualenv still seems to work but maybe that's because it was originally linked when I reinstalled it.
|
I'm using Redhat and have met the same problem.
My solution is :
1. install openssl and openssl-devel ---- yum install openssl openssl-devel -y
2. install krb5-devel ---- yum install krb5-devel
3. change to your python's directory and recompile it ---- make
If I didn't do the 2nd step, when I recompiled my python2.7 , the log would say " fail to build module \_ssl".
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
OSX + homebrew users:
=====================
You can get the latest updates to the recipe:
```
brew reinstall python
```
But if you still get the issue, e.g. maybe you have upgraded your OS, then you may need to get the latest openssl first. You can check which version and where it is used from:
```
openssl version -a
which openssl
```
To get the latest openssl:
```
brew update
brew install openssl
brew link --overwrite --dry-run openssl # safety first.
brew link openssl --overwrite
```
This may issue a warning:
```
bash-4.3$ brew link --overwrite --dry-run openssl
Warning: Refusing to link: openssl Linking keg-only openssl means you may end up linking against the insecure, deprecated system OpenSSL while using the headers from Homebrew's openssl.
Instead, pass the full include/library paths to your compiler e.g.:
-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib
```
Side note: this warning means that for other apps, you may want to use
```
export LDFLAGS=-L/usr/local/opt/openssl/lib
export CPPFLAGS=-I/usr/local/opt/openssl/include
```
Then recompile python:
```
brew uninstall python
brew install python --with-brewed-openssl
```
or for python 3
```
brew uninstall python3
brew install python3 --with-brewed-openssl
```
|
It seems your `pip` requires `HTTPSHandler` which is part of `SSL` library.
**OSX**
On OS X you should link OpenSSL during Python installation (See: [#14497](https://github.com/Homebrew/homebrew/issues/14497)).
For Python 2:
```
brew reinstall python --with-brewed-openssl
pip install --upgrade pip
```
For Python 3:
```
brew reinstall python3 --with-brewed-openssl
pip3 install --upgrade pip
```
You could have multiple Python instances together, to list them run:
```
brew list | grep ^python
```
Or list your version via `ls -al /usr/local/lib/python*`.
|
20,688,034
|
Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
return ep.load()
File "/home/env/.genv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/home/env/.genv/lib/python2.7/site-packages/pip/__init__.py", line 10, in <module>
from pip.util import get_installed_distributions, get_prog
File "/home/env/.genv/lib/python2.7/site-packages/pip/util.py", line 17, in <module>
from pip.vendor.distlib import version
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/version.py", line 13, in <module>
from .compat import string_types
File "/home/env/.genv/lib/python2.7/site-packages/pip/vendor/distlib/compat.py", line 31, in <module>
from urllib2 import (Request, urlopen, URLError, HTTPError,
ImportError: cannot import name HTTPSHandler
```
I used to edit Modules/setup.dist file and uncomment SSL code lines and rebuilt it, with reference to following thread : <http://forums.opensuse.org/english/get-technical-help-here/applications/488962-opensuse-python-openssl-2.html>
|
2013/12/19
|
[
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] |
I was having this problem on Mac OSX, even after confirming my PATH, etc.
Did a; pip uninstall virtualenv then install virtualenv and it seemed to works now.
At the time I had forced brew to link openssl, unlinked it and virtualenv still seems to work but maybe that's because it was originally linked when I reinstalled it.
|
For Ubuntu
==========
First check wheather install openssl-develop
```
sudo apt-get install libssl-dev
```
Try another way to reinstall `pip`
```
sudo apt-get install python-setuptools
sudo easy_install pip
```
use `setuptools` to install pip rather than install with source code may can solve the problem of dependency.
|
1,045,906
|
I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6.
I have had no problems installing any other modules so far, but am getting errors installing pyCurl.
The error:
```
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy
sh: curl-config: not found
Traceback (most recent call last):
File "/opt/ActivePython-2.6/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in <lambda>
File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in <lambda>
File "setup.py", line 90, in <module>
Exception: `curl-config' not found -- please install the libcurl development files
```
My system does have libcurl installed, but ActivePython doesn't seem to find it.
Any ideas will help!
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1045906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124485/"
] |
I couldn't find a curl-config to add to the path, which makes sense as it's not a module that can be called (as far as I can tell)
The answer ended up being a bit of a hack, but it works.
As I had pyCurl working in my native python2.6 install, I simply copied the curl and pycurl items from the native install into the ActivePython install.
|
It looks like `curl-config` isn't in your path. Try running it from the command line and adjust the `PATH` environment variable as needed so that Python can find it.
|
1,045,906
|
I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6.
I have had no problems installing any other modules so far, but am getting errors installing pyCurl.
The error:
```
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy
sh: curl-config: not found
Traceback (most recent call last):
File "/opt/ActivePython-2.6/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in <lambda>
File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in <lambda>
File "setup.py", line 90, in <module>
Exception: `curl-config' not found -- please install the libcurl development files
```
My system does have libcurl installed, but ActivePython doesn't seem to find it.
Any ideas will help!
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1045906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124485/"
] |
```
$ apt-cache depends python-pycurl
python-pycurl
Depends: libc6
Depends: libcurl3-gnutls
Depends: libgnutls26
Depends: libidn11
Depends: libkrb53
Depends: libldap-2.4-2
Depends: zlib1g
Depends: python
Depends: python
Depends: python-central
[...]
```
So first install the dependencies via `sudo aptitude install libcurl3-gnutls` (or the package manager of your distribution) and then run `easy_install pycurl`.
|
It looks like `curl-config` isn't in your path. Try running it from the command line and adjust the `PATH` environment variable as needed so that Python can find it.
|
1,045,906
|
I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6.
I have had no problems installing any other modules so far, but am getting errors installing pyCurl.
The error:
```
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy
sh: curl-config: not found
Traceback (most recent call last):
File "/opt/ActivePython-2.6/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in <lambda>
File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in <lambda>
File "setup.py", line 90, in <module>
Exception: `curl-config' not found -- please install the libcurl development files
```
My system does have libcurl installed, but ActivePython doesn't seem to find it.
Any ideas will help!
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1045906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124485/"
] |
Following dependencies are needed for installing pycurl:
```
apt-cache depends python-pycurl
python-pycurl
Depends: libc6
Depends: libcurl3-gnutls
Depends: libgcrypt11
Depends: python2.7
Depends: python
Depends: python
Suggests: libcurl4-gnutls-dev
Suggests: python-pycurl-dbg
Conflicts: <python2.3-pycurl>
Conflicts: <python2.3-pycurl:i386>
Conflicts: <python2.4-pycurl>
Conflicts: <python2.4-pycurl:i386>
Replaces: <python2.3-pycurl>
Replaces: <python2.3-pycurl:i386>
Replaces: <python2.4-pycurl>
Replaces: <python2.4-pycurl:i386>
Conflicts: python-pycurl:i386
```
Run this command
```
sudo apt-get install libcurl4-gnutls-dev librtmp-dev
```
Then you can install pycurl using
```
pip install pycurl
```
or
```
easy_install pycurl
```
|
It looks like `curl-config` isn't in your path. Try running it from the command line and adjust the `PATH` environment variable as needed so that Python can find it.
|
1,045,906
|
I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6.
I have had no problems installing any other modules so far, but am getting errors installing pyCurl.
The error:
```
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy
sh: curl-config: not found
Traceback (most recent call last):
File "/opt/ActivePython-2.6/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in <lambda>
File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in <lambda>
File "setup.py", line 90, in <module>
Exception: `curl-config' not found -- please install the libcurl development files
```
My system does have libcurl installed, but ActivePython doesn't seem to find it.
Any ideas will help!
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1045906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124485/"
] |
Following dependencies are needed for installing pycurl:
```
apt-cache depends python-pycurl
python-pycurl
Depends: libc6
Depends: libcurl3-gnutls
Depends: libgcrypt11
Depends: python2.7
Depends: python
Depends: python
Suggests: libcurl4-gnutls-dev
Suggests: python-pycurl-dbg
Conflicts: <python2.3-pycurl>
Conflicts: <python2.3-pycurl:i386>
Conflicts: <python2.4-pycurl>
Conflicts: <python2.4-pycurl:i386>
Replaces: <python2.3-pycurl>
Replaces: <python2.3-pycurl:i386>
Replaces: <python2.4-pycurl>
Replaces: <python2.4-pycurl:i386>
Conflicts: python-pycurl:i386
```
Run this command
```
sudo apt-get install libcurl4-gnutls-dev librtmp-dev
```
Then you can install pycurl using
```
pip install pycurl
```
or
```
easy_install pycurl
```
|
I couldn't find a curl-config to add to the path, which makes sense as it's not a module that can be called (as far as I can tell)
The answer ended up being a bit of a hack, but it works.
As I had pyCurl working in my native python2.6 install, I simply copied the curl and pycurl items from the native install into the ActivePython install.
|
1,045,906
|
I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6.
I have had no problems installing any other modules so far, but am getting errors installing pyCurl.
The error:
```
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0
Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz
Processing pycurl-7.19.0.tar.gz
Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy
sh: curl-config: not found
Traceback (most recent call last):
File "/opt/ActivePython-2.6/bin/easy_install", line 8, in <module>
load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in <lambda>
File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup
dist.run_commands()
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands
self.run_command(cmd)
File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command
cmd_obj.run()
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run
File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in <lambda>
File "setup.py", line 90, in <module>
Exception: `curl-config' not found -- please install the libcurl development files
```
My system does have libcurl installed, but ActivePython doesn't seem to find it.
Any ideas will help!
|
2009/06/25
|
[
"https://Stackoverflow.com/questions/1045906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124485/"
] |
Following dependencies are needed for installing pycurl:
```
apt-cache depends python-pycurl
python-pycurl
Depends: libc6
Depends: libcurl3-gnutls
Depends: libgcrypt11
Depends: python2.7
Depends: python
Depends: python
Suggests: libcurl4-gnutls-dev
Suggests: python-pycurl-dbg
Conflicts: <python2.3-pycurl>
Conflicts: <python2.3-pycurl:i386>
Conflicts: <python2.4-pycurl>
Conflicts: <python2.4-pycurl:i386>
Replaces: <python2.3-pycurl>
Replaces: <python2.3-pycurl:i386>
Replaces: <python2.4-pycurl>
Replaces: <python2.4-pycurl:i386>
Conflicts: python-pycurl:i386
```
Run this command
```
sudo apt-get install libcurl4-gnutls-dev librtmp-dev
```
Then you can install pycurl using
```
pip install pycurl
```
or
```
easy_install pycurl
```
|
```
$ apt-cache depends python-pycurl
python-pycurl
Depends: libc6
Depends: libcurl3-gnutls
Depends: libgnutls26
Depends: libidn11
Depends: libkrb53
Depends: libldap-2.4-2
Depends: zlib1g
Depends: python
Depends: python
Depends: python-central
[...]
```
So first install the dependencies via `sudo aptitude install libcurl3-gnutls` (or the package manager of your distribution) and then run `easy_install pycurl`.
|
11,696,691
|
I have a Bash script (Bash 3.2, Mac OS X 10.8) that invokes multiple Python scripts in parallel in order to better utilize multiple cores. Each Python script takes a really long time to complete.
The problem is that if I hit Ctrl+C in the middle of the Bash script, the Python scripts do not actually get killed. How can I write the Bash script so that killing it will also kill all its background children?
Here's my original "reduced test case". Unfortunately I seem to have reduced it so much that it no longer demonstrates the problem; my mistake.
```
set -e
cat >work.py <<EOF
import sys, time
for i in range(10):
time.sleep(1)
print "Tick from", sys.argv[1]
EOF
function process {
python ./work.py $1 &
}
process one
process two
wait
```
Here's a complete test case, still highly reduced, but hopefully this one will demonstrate the problem. It reproduces on my machine... but then, two days ago I thought the *old* test case reproduced on my machine, and today it definitely doesn't.
```
#!/bin/bash -e
set -x
cat >work.sh <<EOF
for i in 0 1 2 3 4 5 6 7 8 9; do
sleep 1; echo "still going"
done
EOF
chmod +x work.sh
function kill_all_jobs { jobs -p | xargs kill; }
trap kill_all_jobs SIGINT
function process {
./work.sh $1
}
process one &
wait $!
echo "All done!"
```
This code continues to print `still going` even after Ctrl+C. But if I move the `&` from outside `process` to inside (i.e.: `./work.sh $1 &`), then Ctrl+C works as expected. I don't understand this at all!
In my real script, `process` contains more than one command, and the commands are long-running and must run in sequence; so I don't know how to "move the `&` inside `process`" in that case. I'm sure it's possible, but it must be non-trivial.
```
$ bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12)
Copyright (C) 2007 Free Software Foundation, Inc.
```
EDIT: Many thanks to @AlanCurry for teaching me some Bash stuff. Unfortunately I still don't understand exactly what's going on in my examples, but it's practically a moot point, as Alan *also* helpfully pointed out that for my real-world parallelization problem, Bash is the wrong tool and I ought to be using a simple makefile with `make -j3`! `make` runs things in parallel where possible, and also understands Ctrl+C perfectly; problem solved (even though question unanswered).
|
2012/07/27
|
[
"https://Stackoverflow.com/questions/11696691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1424877/"
] |
You can't use this structure:
```
do
{
window.setTimeout(fadeIn,1000);
} while(done == false);
```
Because the code in the `setTimeout()` runs sometime LATER, your value of done will NEVER be changed and this loop will run forever. And, as long as it runs, the `setTimeout()` never gets to fire either (because javascript is single threaded).
Instead, what you should do is launch the next `setTimeout(fadeIn, 1000)` from the `fadeIn()` function if you aren't done.
```
function fadeOut()
{
if(parseFloat(current.style.opacity)-0.1>.0000001)
{
current.style.opacity = parseFloat(current.style.opacity) -0.1;
setTimeout(fadeOut, 1000);
}
else
{
current.style.opacity = 0.0;
}
}
```
|
Remember that javascript is single-threaded, so your setTimeout'et functions will not be called until it is finished running the current script. Which will never happen since you're in a loop that's never gonna end (untill you're out of memory from all those setTimeout's). Just call setTimeout once and let the function return. And forget the idea of waiting for it to have happened.
|
19,489,132
|
What is the proper way to pass values of string variables to Popen function in Python? I tried the below piece of code
```
var1 = 'hello'
var2 = 'universe'
p=Popen('/usr/bin/python /apps/sample.py ' + '"' + str(eval('var1')) + ' ' + '"' + str(eval('var2')), shell=True)
```
and in sample.py, below is the code
```
print sys.argv[1]
print '\n'
print sys.argv[2]
```
but it prints the below output
```
hello universe
none
```
so its considering both var1 and var2 as one argument. Is this the right approach of passing values of string variables as arguments?
|
2013/10/21
|
[
"https://Stackoverflow.com/questions/19489132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663585/"
] |
This should work:
```
p = Popen('/usr/bin/python /apps/sample.py {} {}'.format(var1, var2), shell=True)
```
Learn about [string formatting](http://docs.python.org/2/library/string.html#format-examples) .
Second, passing arguments to scripts has its quirks: <http://docs.python.org/2/library/subprocess.html#subprocess.Popen>
This works for me:
test.py:
```
#!/usr/bin/env python
import sys
print sys.argv[1]
print '\n'
print sys.argv[2]
```
Then:
```
chmod +x test.py
```
Then:
```
Python 2.7.4 (default, Jul 5 2013, 08:21:57)
>>> from subprocess import Popen
>>> p = Popen('./test.py {} {}'.format('hello', 'universe'), shell=True)
>>> hello
universe
```
|
```
var1 = 'hello'
var2 = 'universe'
p=Popen("/usr/bin/python /apps/sample.py %s %s"%(str(eval('var1')), str(eval('var2'))), shell=True)
```
Passing format specifier is nice way to do it.
|
48,234,112
|
I want to print all elements in this list in reversed order and every element in this list must be on a new line.
For example if the list is ['i', 'am', 'programming', 'with', 'python'] it should print out:
python
with
programming
am
i
What is the best way to do this?
```
def list():
words = []
while True:
output = input("Type a word: ")
if output == "stop":
break
else:
words.append(output)
for elements in words:
print(elements)
list()
```
|
2018/01/12
|
[
"https://Stackoverflow.com/questions/48234112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9160869/"
] |
You don't need to convert to a data table for every step, it would be easier to query if you moved away from that.
```
var query =
from row in dt.AsEnumerable()
group new
{
premA = row.Field<decimal>("PREM_A"),
premB = row.Field<decimal>("PREM_B"),
} by row.Field<string>("ID").Trim() into g
let premA = g.Sum(x => x.premA)
let premB = g.Sum(x => x.premB)
where premA != 0M || premB != 0M
select new
{
Id = g.Key,
PremA = premA,
PremB = premB,
};
```
|
Also:
```
var resultsDt = dt.AsEnumerable()
.GroupBy(row => row.Field<string>("ID"))
.Select(grp =>new {Id= grp.Key,
PREM_A= grp.Sum(r => r.Field<decimal>("PREM_A")),
PREM_B=grp.Sum(r => r.Field<decimal>("PREM_B"))
})
.Where(e=>e.PREM_A!=0 || e.PREM_B!=0);
```
|
64,802,573
|
I am trying to get the most basic of OpenAPI server to work as expected. It works as expected with auto-generated python-flask but not with aspnet where exceptions being raised on queries occurs.
What extra steps are required to get the aspnet server to respond correctly to queries?
The YAML is as below:
```
openapi: 3.0.0
info:
title: Test API
version: 0.0.0
servers:
- url: http://localhost:{port}
description: Local server
variables:
port:
default: "8092"
paths:
/things:
get:
summary: Return a list of Things
responses:
'200':
description: A JSON array of Things
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Thing"
components:
schemas:
Thing:
properties:
id:
type: integer
name:
type: string
```
In order to get the server to run, the auto-generated launchSettings.json has to be modified from:
```
...
"web": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
...
```
to:
```
...
"web": {
"commandName": "Project",
"launchBrowser": false,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:8092",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
...
```
The console suggests that the server is running ok
```
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\jonathan.noble\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Hosting environment: Development
Content root path: D:\aspnetcore-server-generated\src\IO.Swagger
Now listening on: http://localhost:8092
Application started. Press Ctrl+C to shut down.
```
However, when a query is made via`http://localhost:8092/things` (this is what the swagger editor suggests to use) the server throws an exception with
```
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:8092/things
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HM46UOD2UM1E", Request id "0HM46UOD2UM1E:00000001": An unhandled exception was thrown by the application.
System.UriFormatException: Invalid URI: The URI is empty.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString)
at IO.Swagger.Startup.<ConfigureServices>b__5_2(SwaggerGenOptions c) in D:\aspnetcore-server-generated\src\IO.Swagger\Startup.cs:line 73
at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
...
```
|
2020/11/12
|
[
"https://Stackoverflow.com/questions/64802573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133232/"
] |
You can set a **cookie** for detection users; for example, for the first, I visit your store, you set a cookie with **GUID** value for me, now when I order something, you use my GUID as an identifier to track my order.
|
add AllowAnonymous attribute to actions or controllers. Then user don't need to do log in.
```
[
[AllowAnonymous]
public class Orders: Controller
{
[AllowAnonymous]
public ActionResult PlaceOrder()
{
}
public ActionResult Get()
{
}
}
```
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
>
> subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
>
>
>
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
```
|
use spawn
```
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
```
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
>
> subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
>
>
>
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
```
|
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it:
```
import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line
p.wait()
print p.returncode
```
Or, if you don't care what the external program actually does:
```
cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()
```
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
use spawn
```
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
```
|
this worked for me fine!
`shell_command = "ls -l"
subprocess.call(shell_command.split())`
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it:
```
import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line
p.wait()
print p.returncode
```
Or, if you don't care what the external program actually does:
```
cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()
```
|
use spawn
```
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
```
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
>
> subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
>
>
>
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
```
|
The subprocess module has come along way since 2008. In particular [`check_call`](http://docs.python.org/library/subprocess.html#subprocess.check_call) and [`check_output`](http://docs.python.org/library/subprocess.html#subprocess.check_output) make simple subprocess stuff even easier. The `check_*` family of functions are nice it that they raise an exception if something goes wrong.
```
import os
import subprocess
files = os.listdir('.')
for f in files:
subprocess.check_call( [ 'myscript', f ] )
```
Any output generated by `myscript` will display as though your process produced the output (technically `myscript` and your python script share the same stdout). There are a couple of ways to avoid this.
* `check_call( [ 'myscript', f ], stdout=subprocess.PIPE )`
The stdout will be supressed (beware if `myscript` produces more that 4k of output). stderr will still be shown unless you add the option `stderr=subprocess.PIPE`.
* `check_output( [ 'myscript', f ] )`
`check_output` returns the stdout as a string so it isnt shown. stderr is still shown unless you add the option `stderr=subprocess.STDOUT`.
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
>
> subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
>
>
>
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
```
|
this worked for me fine!
`shell_command = "ls -l"
subprocess.call(shell_command.split())`
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
>
> subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
>
>
>
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
```
|
I use os.system
```
import os
os.system("pdftoppm -png {} {}".format(path2pdf, os.path.join(tmpdirname, "temp")))
```
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it:
```
import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line
p.wait()
print p.returncode
```
Or, if you don't care what the external program actually does:
```
cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()
```
|
I use os.system
```
import os
os.system("pdftoppm -png {} {}".format(path2pdf, os.path.join(tmpdirname, "temp")))
```
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it:
```
import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line
p.wait()
print p.returncode
```
Or, if you don't care what the external program actually does:
```
cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()
```
|
The `os.exec*()` functions *replace* the current programm with the new one. When this programm ends so does your process. You probably want `os.system()`.
|
325,463
|
I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do? Do I have to `fork()` before `calling os.execlp()`?
|
2008/11/28
|
[
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] |
You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it:
```
import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line
p.wait()
print p.returncode
```
Or, if you don't care what the external program actually does:
```
cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()
```
|
this worked for me fine!
`shell_command = "ls -l"
subprocess.call(shell_command.split())`
|
46,138,803
|
I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python -V
```
It gives me:
```
Python 3.5.2 :: Anaconda 4.1.1 (64-bit)
```
I run `set python` to see the Environment variables, which gives me:
```
Environment variable python not defined
```
An annoying thing is that, this is a lab machine which I don't have the admin right, I need to email the IT Admin to change the Environment variables.
Tried:`virtualenv -p python env`
It gives me:
```
The path python (from --python=python) does not exist
```
Seems there is no way around until the environment variable is fixed.
|
2017/09/10
|
[
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] |
After reading this [tutorial](https://cloud.google.com/python/setup), I found the workaround for my case:
```
virtualenv --python "C:\\Anaconda3\\python.exe" env
```
|
If `python --V` is showing a version greater than 3, then why not try:
```
virtualenv -p python env
```
instead? The value of the `p` flag is simply referring to the version of python you're wanting to create the virtual environment with. In this case, `python` is greater than version 3.
|
46,138,803
|
I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python -V
```
It gives me:
```
Python 3.5.2 :: Anaconda 4.1.1 (64-bit)
```
I run `set python` to see the Environment variables, which gives me:
```
Environment variable python not defined
```
An annoying thing is that, this is a lab machine which I don't have the admin right, I need to email the IT Admin to change the Environment variables.
Tried:`virtualenv -p python env`
It gives me:
```
The path python (from --python=python) does not exist
```
Seems there is no way around until the environment variable is fixed.
|
2017/09/10
|
[
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] |
If `python --V` is showing a version greater than 3, then why not try:
```
virtualenv -p python env
```
instead? The value of the `p` flag is simply referring to the version of python you're wanting to create the virtual environment with. In this case, `python` is greater than version 3.
|
Use something like this: **virtualenv --python "*Your python.exe path*" '*Name of your virtual folder*'**. You can take your python.exe path from your environment variables which is in properties of your '*This PC*' or '*My Computer*'.
Then get into the folder and run the command: ***.\Scripts\activate***
Enter the command pip freeze to make sure you have created your virtual environment successfully! It should return nothing since it is like an empty basket. Look at[](https://i.stack.imgur.com/vakFI.png) how it comes in the picture.
|
46,138,803
|
I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python -V
```
It gives me:
```
Python 3.5.2 :: Anaconda 4.1.1 (64-bit)
```
I run `set python` to see the Environment variables, which gives me:
```
Environment variable python not defined
```
An annoying thing is that, this is a lab machine which I don't have the admin right, I need to email the IT Admin to change the Environment variables.
Tried:`virtualenv -p python env`
It gives me:
```
The path python (from --python=python) does not exist
```
Seems there is no way around until the environment variable is fixed.
|
2017/09/10
|
[
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] |
If `python --V` is showing a version greater than 3, then why not try:
```
virtualenv -p python env
```
instead? The value of the `p` flag is simply referring to the version of python you're wanting to create the virtual environment with. In this case, `python` is greater than version 3.
|
Just a comment: On my Win10, for python3 scripts, I run py c:\path\to\script.
For example:
```
py -m pip --version
```
So to make the above command work, I used:
```
py -m venv env
```
and:
```
virtualenv -p py env
```
So that could be a possible solution as well.
|
46,138,803
|
I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python -V
```
It gives me:
```
Python 3.5.2 :: Anaconda 4.1.1 (64-bit)
```
I run `set python` to see the Environment variables, which gives me:
```
Environment variable python not defined
```
An annoying thing is that, this is a lab machine which I don't have the admin right, I need to email the IT Admin to change the Environment variables.
Tried:`virtualenv -p python env`
It gives me:
```
The path python (from --python=python) does not exist
```
Seems there is no way around until the environment variable is fixed.
|
2017/09/10
|
[
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] |
After reading this [tutorial](https://cloud.google.com/python/setup), I found the workaround for my case:
```
virtualenv --python "C:\\Anaconda3\\python.exe" env
```
|
Use something like this: **virtualenv --python "*Your python.exe path*" '*Name of your virtual folder*'**. You can take your python.exe path from your environment variables which is in properties of your '*This PC*' or '*My Computer*'.
Then get into the folder and run the command: ***.\Scripts\activate***
Enter the command pip freeze to make sure you have created your virtual environment successfully! It should return nothing since it is like an empty basket. Look at[](https://i.stack.imgur.com/vakFI.png) how it comes in the picture.
|
46,138,803
|
I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python -V
```
It gives me:
```
Python 3.5.2 :: Anaconda 4.1.1 (64-bit)
```
I run `set python` to see the Environment variables, which gives me:
```
Environment variable python not defined
```
An annoying thing is that, this is a lab machine which I don't have the admin right, I need to email the IT Admin to change the Environment variables.
Tried:`virtualenv -p python env`
It gives me:
```
The path python (from --python=python) does not exist
```
Seems there is no way around until the environment variable is fixed.
|
2017/09/10
|
[
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] |
After reading this [tutorial](https://cloud.google.com/python/setup), I found the workaround for my case:
```
virtualenv --python "C:\\Anaconda3\\python.exe" env
```
|
Just a comment: On my Win10, for python3 scripts, I run py c:\path\to\script.
For example:
```
py -m pip --version
```
So to make the above command work, I used:
```
py -m venv env
```
and:
```
virtualenv -p py env
```
So that could be a possible solution as well.
|
46,138,803
|
I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python -V
```
It gives me:
```
Python 3.5.2 :: Anaconda 4.1.1 (64-bit)
```
I run `set python` to see the Environment variables, which gives me:
```
Environment variable python not defined
```
An annoying thing is that, this is a lab machine which I don't have the admin right, I need to email the IT Admin to change the Environment variables.
Tried:`virtualenv -p python env`
It gives me:
```
The path python (from --python=python) does not exist
```
Seems there is no way around until the environment variable is fixed.
|
2017/09/10
|
[
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] |
Use something like this: **virtualenv --python "*Your python.exe path*" '*Name of your virtual folder*'**. You can take your python.exe path from your environment variables which is in properties of your '*This PC*' or '*My Computer*'.
Then get into the folder and run the command: ***.\Scripts\activate***
Enter the command pip freeze to make sure you have created your virtual environment successfully! It should return nothing since it is like an empty basket. Look at[](https://i.stack.imgur.com/vakFI.png) how it comes in the picture.
|
Just a comment: On my Win10, for python3 scripts, I run py c:\path\to\script.
For example:
```
py -m pip --version
```
So to make the above command work, I used:
```
py -m venv env
```
and:
```
virtualenv -p py env
```
So that could be a possible solution as well.
|
53,495,570
|
I need to install `graph-tool` from source, so I add in my Dockerfile this:
```
FROM ubuntu:18.04
RUN git clone https://git.skewed.de/count0/graph-tool.git
RUN cd graph-tool && ./configure && make && make install
```
as it written [here](https://git.skewed.de/count0/graph-tool/wikis/Installation-instructions#manual-compilation).
When I try to build my Docker-compose I catch a error:
```
/bin/sh: 1: ./configure: not found
```
What am I doing wrong? Thanks!
ADDED Full Dockerfile:
```
FROM ubuntu:16.04
ENV LANG C.UTF-8
ENV PYTHONUNBUFFERED 1
ENV C_FORCE_ROOT true
# Install dependencies
RUN apt-get update \
&& apt-get install -y git \
&& apt-get install -y python3-pip python3-dev \
&& apt-get install -y binutils libproj-dev gdal-bin \
&& cd /usr/local/bin \
&& ln -s /usr/bin/python3 python \
&& pip3 install --upgrade pip
RUN git clone https://git.skewed.de/count0/graph-tool.git
RUN apt-get update && apt-get install -y gcc
RUN apt-get update && apt-get install -y libboost-all-dev
RUN apt update && apt install -y --no-install-recommends \
make \
build-essential \
g++
RUN cd graph-tool && ./configure && make && make install
# Project specific setups
RUN mkdir /code
WORKDIR /code
ADD . /code
RUN pip3 install -r requirements.txt
```
|
2018/11/27
|
[
"https://Stackoverflow.com/questions/53495570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9098575/"
] |
You need to run **autogen.sh** first, it will generate **configure** file
P.S. Make sure you install libtool
```
apt-get install libtool
```
|
You have to install the prerequisites first.
```
RUN apt update && apt install -y --no-install-recommends \
make \
build-essential \
g++ \
....
```
Don't forget to clean up and remove temp/unnecessary files!
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
Why don't you use JNA API `http://www.java2s.com/Code/Jar/j/Downloadjna351jar.htm` to load native library? Once you putted into your project classpath, you add this code
`NativeLibrary.addSearchPath("libtesseract302", "your native lib path");` make sure you have this libtesseract302.dll file, normally it is located at `windows32` folder.
For example, if your libtesseract302.dll file in somewhere `c:/abcv/aaa/libtesseract302.dll` then you just set the path like this `NativeLibrary.addSearchPath("libtesseract302", "c:/abcv/aaa");`
I don't know how windows path look like either `c:/abcv/aaa` or `c:\\abcv\\aaa\\`
if you want easier way, just put all your necessary dll file into your windows32 folder, JVM will take care of it.
Another issue might be you were not installing the application correctly or the application version is unmatch with your jar version. try to install the latest application and download the latest jar to try again. Hope it helps :)
|
A few days ago I ran into the same error message when trying to load a C++ DLL with JNA. It turned out that the cause was a missing DLL that my DLL depended on.
In my case it was the MS Visual Studio 2012 redistributable, which I then downloaded and installed on the machine and the problem was gone. Try using **Dependency Walker** to find any missing libraries and install them.
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
The error stems from your trying to load 32-bit DLLs in 64-bit JVM. The possible solution is switch to 32-bit JVM; alternatively, use [64-bit Tesseract and Leptonica DLLs](https://github.com/charlesw/tesseract/tree/master/src/lib/TesseractOcr/x64).
|
A few days ago I ran into the same error message when trying to load a C++ DLL with JNA. It turned out that the cause was a missing DLL that my DLL depended on.
In my case it was the MS Visual Studio 2012 redistributable, which I then downloaded and installed on the machine and the problem was gone. Try using **Dependency Walker** to find any missing libraries and install them.
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
The error stems from your trying to load 32-bit DLLs in 64-bit JVM. The possible solution is switch to 32-bit JVM; alternatively, use [64-bit Tesseract and Leptonica DLLs](https://github.com/charlesw/tesseract/tree/master/src/lib/TesseractOcr/x64).
|
I had the same problem and found that this "resource path" is not set by "native directory path" .
You can however add new folders to it by using "Add External Class Folder" in the Library tab, even if this folder does not contain any class file but native library files(like DLL on Windows)
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
The error stems from your trying to load 32-bit DLLs in 64-bit JVM. The possible solution is switch to 32-bit JVM; alternatively, use [64-bit Tesseract and Leptonica DLLs](https://github.com/charlesw/tesseract/tree/master/src/lib/TesseractOcr/x64).
|
Had the same issue, sorted with the following lines
```
System.load("/usr/local/lib/liblept.so.5")
System.loadLibrary("tesseract")
```
For your case, it might be different libraries but in the end is pretty much the same: just load the libraries that you need manually.
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
Had the same issue, sorted with the following lines
```
System.load("/usr/local/lib/liblept.so.5")
System.loadLibrary("tesseract")
```
For your case, it might be different libraries but in the end is pretty much the same: just load the libraries that you need manually.
|
I think an easier way to get around this error would be to revert to an earlier version where you were not getting this error. Right click on the project folder and navigate to local history to revert to an earlier version. I verified this workaround on the android studio installed on Mac OS Big sur.
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
Like the error says, it's looking for `win32-x86-64/libtesseract302.dll` in `java.class.path`. Part of your classpath apparently includes `myproject/target/classes`.
The prefix represents the platform and architecture of the shared library to be loaded, which allows shared libraries for different targets to be included in the same archive. If JNA cannot find the requested library name in the system load path, then it attempts to find it within your resource path (extracting it, if necessary). So if you put the DLL in a jar file, you'll need to give it the `win32-x86-64` prefix in order for it to load.
The "resource path" is nominally your class path; basically anywhere reachable by `ClassLoader.getResource()`.
|
I think an easier way to get around this error would be to revert to an earlier version where you were not getting this error. Right click on the project folder and navigate to local history to revert to an earlier version. I verified this workaround on the android studio installed on Mac OS Big sur.
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
Like the error says, it's looking for `win32-x86-64/libtesseract302.dll` in `java.class.path`. Part of your classpath apparently includes `myproject/target/classes`.
The prefix represents the platform and architecture of the shared library to be loaded, which allows shared libraries for different targets to be included in the same archive. If JNA cannot find the requested library name in the system load path, then it attempts to find it within your resource path (extracting it, if necessary). So if you put the DLL in a jar file, you'll need to give it the `win32-x86-64` prefix in order for it to load.
The "resource path" is nominally your class path; basically anywhere reachable by `ClassLoader.getResource()`.
|
I had the same problem and found that this "resource path" is not set by "native directory path" .
You can however add new folders to it by using "Add External Class Folder" in the Library tab, even if this folder does not contain any class file but native library files(like DLL on Windows)
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
The error stems from your trying to load 32-bit DLLs in 64-bit JVM. The possible solution is switch to 32-bit JVM; alternatively, use [64-bit Tesseract and Leptonica DLLs](https://github.com/charlesw/tesseract/tree/master/src/lib/TesseractOcr/x64).
|
Why don't you use JNA API `http://www.java2s.com/Code/Jar/j/Downloadjna351jar.htm` to load native library? Once you putted into your project classpath, you add this code
`NativeLibrary.addSearchPath("libtesseract302", "your native lib path");` make sure you have this libtesseract302.dll file, normally it is located at `windows32` folder.
For example, if your libtesseract302.dll file in somewhere `c:/abcv/aaa/libtesseract302.dll` then you just set the path like this `NativeLibrary.addSearchPath("libtesseract302", "c:/abcv/aaa");`
I don't know how windows path look like either `c:/abcv/aaa` or `c:\\abcv\\aaa\\`
if you want easier way, just put all your necessary dll file into your windows32 folder, JVM will take care of it.
Another issue might be you were not installing the application correctly or the application version is unmatch with your jar version. try to install the latest application and download the latest jar to try again. Hope it helps :)
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
Like the error says, it's looking for `win32-x86-64/libtesseract302.dll` in `java.class.path`. Part of your classpath apparently includes `myproject/target/classes`.
The prefix represents the platform and architecture of the shared library to be loaded, which allows shared libraries for different targets to be included in the same archive. If JNA cannot find the requested library name in the system load path, then it attempts to find it within your resource path (extracting it, if necessary). So if you put the DLL in a jar file, you'll need to give it the `win32-x86-64` prefix in order for it to load.
The "resource path" is nominally your class path; basically anywhere reachable by `ClassLoader.getResource()`.
|
A few days ago I ran into the same error message when trying to load a C++ DLL with JNA. It turned out that the cause was a missing DLL that my DLL depended on.
In my case it was the MS Visual Studio 2012 redistributable, which I then downloaded and installed on the machine and the problem was gone. Try using **Dependency Walker** to find any missing libraries and install them.
|
19,768,456
|
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [partial(no_op, el) for el in seq]
for func in (loop_one, loop_two):
print [f() for f in func(sequence)]
```
The output of the above is:
```
['spam', 'spam', 'spam']
['foo', 'bar', 'spam']
```
The behaviour of `loop_one` is surprising to me as I would expect it to behave as `loop_two`:`el` is an immutable value (a string) that changes at each loop, but **`lambda` seems to store a pointer to the "looping variable"**, like if the loop would recycle the same memory address for each element of the sequence.
The above behaviour is the same with full-blown functions with a for loop in them (so it is not a list-comprehension syntax).
**But wait: there is more... and more puzzling!**
The following script works like `loop_one`:
```
b = []
for foo in ("foo", "bar"):
b.append(lambda: foo)
print [a() for a in b]
```
(output: `['bar', 'bar']`)
But watch what happens when one substitute the variable name `foo` with `a`:
```
b = []
for a in ("foo", "bar"):
b.append(lambda: a)
print [a() for a in b]
```
(output: `[<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>]`)
Any idea of what is happening here? I suspect there must be some gotcha related to the underlying C implementation of my interpreter, but I haven't anything else (Jthon, PyPy or similar) to test if this behaviour is consistent across different implementations.
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] |
Like the error says, it's looking for `win32-x86-64/libtesseract302.dll` in `java.class.path`. Part of your classpath apparently includes `myproject/target/classes`.
The prefix represents the platform and architecture of the shared library to be loaded, which allows shared libraries for different targets to be included in the same archive. If JNA cannot find the requested library name in the system load path, then it attempts to find it within your resource path (extracting it, if necessary). So if you put the DLL in a jar file, you'll need to give it the `win32-x86-64` prefix in order for it to load.
The "resource path" is nominally your class path; basically anywhere reachable by `ClassLoader.getResource()`.
|
Why don't you use JNA API `http://www.java2s.com/Code/Jar/j/Downloadjna351jar.htm` to load native library? Once you putted into your project classpath, you add this code
`NativeLibrary.addSearchPath("libtesseract302", "your native lib path");` make sure you have this libtesseract302.dll file, normally it is located at `windows32` folder.
For example, if your libtesseract302.dll file in somewhere `c:/abcv/aaa/libtesseract302.dll` then you just set the path like this `NativeLibrary.addSearchPath("libtesseract302", "c:/abcv/aaa");`
I don't know how windows path look like either `c:/abcv/aaa` or `c:\\abcv\\aaa\\`
if you want easier way, just put all your necessary dll file into your windows32 folder, JVM will take care of it.
Another issue might be you were not installing the application correctly or the application version is unmatch with your jar version. try to install the latest application and download the latest jar to try again. Hope it helps :)
|
49,203,174
|
i am trying to install Home Automatization (<https://home-assistant.io>) on my Synology. I've installed python via the synology packaging system, i've done basic setup (<https://home-assistant.io/docs/installation/synology/>) but when i try to run the daemon i see this in console:
*homeassistant requires Python '>=3.5.3' but the running Python is 3.5.1*
Is there any chance to update the python to required version on synology? Can you help me please?
|
2018/03/09
|
[
"https://Stackoverflow.com/questions/49203174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9469908/"
] |
I faced exactly the same issue where I needed to keep previous user answers for a conversation. Take a look at [Handler](https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.handler.html]) documentation which is a base class for all handlers. It has parameter called pass\_user\_data. When set to True it passes user\_data dictionary to your handler and it's related to the user the update was sent from. You can utilize it to achieve what you are looking for.
Let's say I have a conversation with an entry point and two states:
```
def build_conversation_handler():
conversation_handler = ConversationHandler(
entry_points=[CommandHandler('command', callback=show_options)],
states={
PROCESS_SELECT: [CallbackQueryHandler(process_select, pass_user_data=True)],
SOME_OTHER: [MessageHandler(filters=Filters.text, callback=some_other, pass_user_data=True)],
},
)
```
Here are the handlers for the conversation:
```
def show_options(bot, update):
button_list = [
[InlineKeyboardButton("Option 1", callback_data="Option 1"),
InlineKeyboardButton("Option 2", callback_data="Option 2")]]
update.message.reply_text("Here are your options:", reply_markup=InlineKeyboardMarkup(button_list))
return PROCESS_SELECT
def process_select(bot, update, user_data):
query = update.callback_query
selection = query.data
# save selection into user data
user_data['selection'] = selection
return SOME_OTHER
def some_other(bot, update, user_data):
# here I get my old selection
old_selection = user_data['selection']
```
In the first handler I show user keyboard to choose an option, in the next handler I grab selection from callback query and store it into user data. The last handler is a message handler so it has no callback data, but since I added user\_data to it I can access the dictionary with the data that I added previously. With this approach you can store and access anything between the handlers that will be related to a user.
|
I think the accepted solution is deprecated -
<https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.handler.html>
>
> pass\_user\_data and pass\_chat\_data determine whether a dict you can use to keep any data in will be sent to the callback function. Related to either the user or the chat that the update was sent in. For each update from the same user or in the same chat, it will be the same dict.
>
>
> Note that this is DEPRECATED, and you should use context based callbacks. See <https://git.io/fxJuV> for more info.
>
>
>
can store state in `context.user_data['var'] = val`
|
48,971,320
|
This may be a very easy question but I'm new to python and I've searched the net however I couldn't solve the problem. I have a csv file which I need to search for a specific word in the columns of its first row. How can I do that?
|
2018/02/25
|
[
"https://Stackoverflow.com/questions/48971320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9201115/"
] |
I used the default csv module of python to read a csv file line by line. Since you specified that we have to search only in the first row, that's why I used break-to stop execution after searching the first row of the csv. You can remove the break, to search throughout the csv. Hope this works.
```
import csv
a='abc' #String that you want to search
with open("testing.csv") as f_obj:
reader = csv.reader(f_obj, delimiter=',')
for line in reader: #Iterates through the rows of your csv
print(line) #line here refers to a row in the csv
if a in line: #If the string you want to search is in the row
print("String found in first row of csv")
break
```
|
```
import csv
a='abc' #String that you want to search
with open("testing.csv") as f_obj:
reader = csv.reader(f_obj, delimiter=',')
for line in reader: #Iterates through the rows of your csv
print(line) #line here refers to a row in the csv
if a in str(line): #If the string you want to search is in the row
print("String found in first row of csv")
break
```
You'll have to add "str(line)" to convert the line to string and then compare it.
|
819,396
|
I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.
Is there a straightforward way to open up the files using the correct file encoding?
|
2009/05/04
|
[
"https://Stackoverflow.com/questions/819396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100758/"
] |
Use the [chardet](http://chardet.feedparser.org/) library to detect the encoding.
|
You can check for the [BOM](http://en.wikipedia.org/wiki/Byte-order_mark "BOM") at the beginning of the file to check whether it's UTF.
Then [unicode.decode](http://docs.python.org/library/stdtypes.html#str.decode) accordingly (using one of the [standard encodings](http://docs.python.org/library/codecs.html#standard-encodings)).
**EDIT**
Or, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDecodeError, then decode it as 'utf\_16\_le'.
|
819,396
|
I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.
Is there a straightforward way to open up the files using the correct file encoding?
|
2009/05/04
|
[
"https://Stackoverflow.com/questions/819396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100758/"
] |
Use the [chardet](http://chardet.feedparser.org/) library to detect the encoding.
|
What's in the files? If it's plain text in a Latin-based alphabet, almost every other byte the UTF-16LE files will be zero. In the windows-1252 files, on the other hand, I wouldn't expect to see any zeros at all. For example, here's `“Hello”` in windows-1252:
```
93 48 65 6C 6C 6F 94
```
...and in UTF-16LE:
```
1C 20 48 00 65 00 6C 00 6C 00 6F 00 1D 20
```
Aside from the curly quotes, each character maps to the same value, with the addition of a trailing zero byte. In fact, that's true for every character in the ISO-8859-1 character set (windows-1252 extends ISO-8859-1 to add mappings for several printing characters—like curly quotes—to replace the control characters in the range `0x80..0x9F`).
If you know all the files are either windows-1252 or UTF-16LE, a quick scan for zeroes should be all you need to figure out which is which. There's a good reason why chardet is so slow and complex, but in this case I think you can get away with quick and dirty.
|
63,141,133
|
I'm new to python and webscraping.
I'm trying to extract the text from a list that starts with `"a href"`.
The whole list is in a variable named `team"`.
If I write `team[0].a.text` I get the first text.
But when I do `team[0:14].a.text` I get this response:
```
AttributeError: 'list' object has no attribute 'a'`
```
I guess that means that the a.text function doesn't work on a list.
How can get a list from of text from this?
Here is a sample of the code as requested:
```
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'http://ligueelite.hockey-richelieu.qc.ca/fr/stats/classement.html?season=2295&subSeason=2296&category=2134'
#opening connection and grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
# html parser
page_soup = soup(page_html, "html.parser")
# grab each team
team = page_soup.findAll("td",{"class":"team"})
```
|
2020/07/28
|
[
"https://Stackoverflow.com/questions/63141133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14011583/"
] |
I hope this simple example helps you udnerstand on your errors more.
**If I say `qjogos = (int(qtjog_entry.get()))` at the main block, like:**
```
from tkinter import *
root = Tk()
def click():
pass
qtjog_entry = Entry(root)
qtjog_entry.pack()
qjogos = (int(qtjog_entry.get()))
b = Button(root,text='Click me',command=click)
b.pack()
root.mainloop()
```
I get youre same error,
```
Traceback (most recent call last):
File "c:/PyProjects/Patient Data Entry/test2.py", line 11, in <module>
qjogos = (int(qtjog_entry.get()))
ValueError: invalid literal for int() with base 10: ''
```
**But now if i say it inside of a function, like:**
```
from tkinter import *
root = Tk()
def click():
qjogos = (int(qtjog_entry.get()))
print(qjogos)
qtjog_entry = Entry(root)
qtjog_entry.pack()
b = Button(root,text='Click me',command=click)
b.pack()
root.mainloop()
```
I dont get any error and the number is printed in the terminal.
What happens in the first code is that, initially when the program runs, the value of whats inside the entry box is `''` (empty sting) which is not an int and hence cannot be converted to an integer using `int()`. So you have to enter the value then click on a button which calls the function and then gets the value which is inside the entrybox at the time you clicked the button.
I hope this is what you meant in your Q and that it clears your doubt, let me know if any more doubts. Explained it more cause you mentioned you're new to programming, cheers :D
|
It looks like `self.qtjog_entry.get()` returns an empty string; you can't use `int()` on an empty string. Without having more context, it's hard to tell exactly what's wrong here.
|
11,254,769
|
Here is the story.
I have a bunch of stored procedures and all have their own argument types.
What I am looking to do is to create a bit of a type safety layer in python so I can make sure all values are of the correct type before hitting the database.
Of course I don't want to write up the whole schema again in python, so I thought I could auto generate this info on startup by fetching the argument names and types from the database.
So I proceed to hack up this query just for testing
```
SELECT proname, proargnames, proargtypes
FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_proc p
ON pronamespace = n.oid
WHERE nspname = 'public';
```
Then I run it from python and for 'proargtypes' I get a string like this for each result
```
'1043 23 1043'
```
My keen eye tells me these are the oids for the postgresql types, seperated by space, and this particular string means the function accepts varchar,integer,varchar.
So in python speak, this should be
```
(unicode, int, unicode)
```
Now how can I get the python types from these numbers?
The ideal end result would be something like this
```
In [129]: get_python_type(23)
Out[129]: int
```
I've looked all through psycopg2 and the closest I've found is 'extensions.string\_types' but that just maps oids to sql type names.
|
2012/06/29
|
[
"https://Stackoverflow.com/questions/11254769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/537925/"
] |
If you want the Python type classes, like you might get from a `SQLALchemy` column object, you'll need to build and maintain your own mapping. `psycopg2` doesn't have one, even internally.
But if what you want is a way to get from an `oid` to a function that will convert raw values into Python instances, `psycopg2.extensions.string_types` is actually already what you need. It might look like it's just a mapping from `oid` to a name, but that's not quite true: its values aren't strings, they're instances of `psycopg2._psycopg.type`. Time to delve into a little code.
`psycopg2` exposes an API for registering new type converters which we can use to trace back into the C code involved with typecasts; this centers around the `typecastObject` in
[typecast.c](https://github.com/psycopg/psycopg2/blob/6becf0ef550e8eb0c241c3835b1466eef37b1784/psycopg/typecast.c), which, unsurprisingly, maps to the `psycopg2._psycopg.type` we find in our old friend `string_types`. This object contains pointers to two functions, `pcast` (for Python casting function) and `ccast` (for C casting function), which would seem like what we want— just pick whichever one exists and call it, problem solved. Except they're not among the attributes exposed (`name`, which is just a label, and `values`, which is a list of oids). What the type does expose to Python is `__call__`, which, it turns out, just chooses between `pcast` and `ccast` for us. The documentation for this method is singularly unhelpful, but looking at the C code further [shows](https://github.com/psycopg/psycopg2/blob/6becf0ef550e8eb0c241c3835b1466eef37b1784/psycopg/typecast.c#L471) that it takes two arguments: a string containing the raw value, and a cursor object.
```
>>> import psycopg2.extensions
>>> cur = something_that_gets_a_cursor_object()
>>> psycopg2.extensions.string_types[23]
<psycopg2._psycopg.type 'INTEGER' at 0xDEADBEEF>
>>> psycopg2.extensions.string_types[23]('100', cur)
100
>>> psycopg2.extensions.string_types[23]('10.0', cur)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.0'
>>> string_types[1114]
<psycopg2._psycopg.type 'DATETIME' at 0xDEADBEEF>
>>> string_types[1114]('2018-11-15 21:35:21', cur)
datetime.datetime(2018, 11, 15, 21, 35, 21)
```
The need for a cursor is unfortunate, and in fact, a cursor isn't always required:
```
>>> string_types[23]('100', None)
100
```
But anything having to with converting actual string (`varchar`, for example) types is dependent on the PostgreSQL server's locale, at least in a Python 3 compilation, and passing `None` to those casters doesn't just fail— it segfaults. The method you mention, `cursor.cast(oid, raw)`, is essentially a wrapper around the casters in `psycopg2.extensions.string_types` and may be more convenient in some instances.
The only workaround for needing a cursor and connection that I can think of would be to build essentially a mock connection object. If it exposed all of the relevant environment information without connecting to an actual database, it could be attached to a cursor object and used with `string_types[oid](raw, cur)` or with `cur.cast(oid, raw)`, but the mock would have be built in C and is left as an exercise to the reader.
|
The mapping of postgres types and python types is given [here](http://packages.python.org/psycopg2/usage.html). Does that help?
Edit:
When you read a record from a table, the postgres (or any database) driver will automatically map the record column types to Python types.
```
cur = con.cursor()
cur.execute("SELECT * FROM Writers")
row = cur.fetchone()
for index, val in enumerate(row):
print "column {0} value {1} of type {2}".format(index, val, type(val))
```
Now, you just have to map Python types to MySQL types while writing your MySQL interface code.
But, frankly, this is a roundabout way of mapping types from PostgreSQL types to MySQL types. I would just refer one of the numerous type mappings between these two databases like [this](http://en.wikibooks.org/wiki/Converting_MySQL_to_PostgreSQL#Data_Types)
|
34,538,890
|
I have a question which is not really clear in python documentation (<https://docs.python.org/2/library/stdtypes.html#set.intersection>).
When using set.intersection the resulting set contains the objects from current set or from other? In the case that both objects have same value but are different objects in memory.
I am using this to compare a previous extraction taken from file with a new one coming from the internet. Both have some objects that are similar but I want to update the old ones.
Or maybe there is a simpler alternative to achieve this? It would me much easier if sets implemented `__getitem__`.
```
oldApsExtract = set()
if (os.path.isfile("Apartments.json")):
with open('Apartments.json', mode='r') as f:
oldApsExtract = set(jsonpickle.decode(f.read()))
newApsExtract = set(getNewExtract())
updatedAps = oldApsExtract.intersection(newApsExtract)
deletedAps = oldApsExtract.difference(newApsExtract)
newAps = newApsExtract.difference(oldApsExtract)
for ap in deletedAps:
ap.mark_deleted()
for ap in updatedAps:
ap.update()
saveAps = list(oldApsExtract) + list(newAps)
with open('Apartments.json', mode='w') as f:
f.write(jsonpickle.encode(saveAps))
```
|
2015/12/30
|
[
"https://Stackoverflow.com/questions/34538890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1936538/"
] |
What objects are used varies, if the sets are the same size the intersecting elements from b, if b has more elements then the objects from a are returned:
```
i = "$foobar" * 100
j = "$foob" * 100
l = "$foobar" * 100
k = "$foob" * 100
print(id(i), id(j))
print(id(l), id(k))
a = {i, j}
b = {k, l, 3}
inter = a.intersection(b)
for ele in inter:
print(id(ele))
```
Output:
```
35510304 35432016
35459968 35454928
35510304
35432016
```
Now when they are the same size:
```
i = "$foobar" * 100
j = "$foob" * 100
l = "$foobar" * 100
k = "$foob" * 100
print(id(i), id(j))
print(id(l), id(k))
a = {i, j}
b = {k, l}
inter = a.intersection(b)
for ele in inter:
print(id(ele))
```
Output:
```
35910288 35859984
35918160 35704816
35704816
35918160
```
There relevant part of the [source](https://github.com/python/cpython/blob/master/Objects/setobject.c#L1294). The line `if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so))`, n the result of the comparison seems to decide which object to iterate over and what objects get used.
```
if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
tmp = (PyObject *)so;
so = (PySetObject *)other;
other = tmp;
}
while (set_next((PySetObject *)other, &pos, &entry)) {
key = entry->key;
hash = entry->hash;
rv = set_contains_entry(so, key, hash);
if (rv < 0) {
Py_DECREF(result);
return NULL;
}
if (rv) {
if (set_add_entry(result, key, hash)) {
Py_DECREF(result);
return NULL;
}
```
If you pass an object that is not a set, then the same is not true and the length is irrelevant as the objects from the iterable are used:
```
it = PyObject_GetIter(other);
if (it == NULL) {
Py_DECREF(result);
return NULL;
}
while ((key = PyIter_Next(it)) != NULL) {
hash = PyObject_Hash(key);
if (hash == -1)
goto error;
rv = set_contains_entry(so, key, hash);
if (rv < 0)
goto error;
if (rv) {
if (set_add_entry(result, key, hash))
goto error;
}
Py_DECREF(key);
```
When you pass an iterable, firstly it could be an iterator so you could not check the size without consuming and if you passed a list then the lookup would be `0(n)` so it makes sense to just iterate over the iterable passed in, in contrast if you have a set of `1000000` elements and one with `10`, it makes sense to check if the `10` are in the set if `1000000` as opposed to checking if any of `1000000` are in your set of `10` as the lookup should be `0(1)` on average so it mean a linear pass over 10 vs a linear pass over 1000000 elements.
If you look at the [wiki.python.org/moin/TimeComplexity](https://wiki.python.org/moin/TimeComplexity), this is backed up:
>
> Average case -> Intersection s&t O(min(len(s), len(t))
>
>
> Worst case -> O(len(s) \* len(t))O(len(s) \* len(t))
>
>
> *replace "min" with "max" if t is not a set*
>
>
>
So when we pass an iterable we should always get the objects from b:
```
i = "$foobar" * 100
j = "$foob" * 100
l = "$foobar" * 100
k = "$foob" * 100
print(id(i), id(j))
print(id(l), id(k))
a = {i, j}
b = [k, l, 1,2,3]
inter = a.intersection(b)
for ele in inter:
print(id(ele))
```
You get the objects from b:
```
20854128 20882896
20941072 20728768
20941072
20728768
```
If you really want to decide what objects you keep then do the iterating and lookups yourself keeping whichever you want.
|
One thing you could do is instead use python dictionaries. Access is still O(1), elements are easy to access, and a simple loop such as follows can get the intersection feature:
```
res=[]
for item in dict1.keys():
if dict2.has_key(item):
res.append(item)
```
The advantage here is you have full control of what is going on, and can tweak it as you need to. For example, can also do things like:
```
if dict1.has_key(item):
dict1[item]=updatedValue
```
|
64,839,088
|
I'm trying to use the OpenCV Stitcher class for putting two images together. I ran the simple example provided in the answer to this [question](https://stackoverflow.com/questions/34362922/how-to-use-opencv-stitcher-class-with-python) with the same koala images, but it returns `(1, None)` every time. I've tried this on opencv-python version 3.4, 4.2, and 4.4, and all have the same result.
I've tried replacing the stitcher initializer with something else, (`cv2.Stitcher.create`, `cv2.Stitcher_create`, `cv2.createStitcher`), but nothing seems to work. If it helps, I'm on Mac Catalina, using Python 3.7. Thanks!
|
2020/11/14
|
[
"https://Stackoverflow.com/questions/64839088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7129536/"
] |
Try changing the default pano confidence threshold using `setPanoConfidenceThresh()`. By default it's 1.0, and apparently it results in the stitcher thinking that it has failed.
Here is the full example that works for me. I used that pair of koala images as well, and I am on opencv 4.2.0:
```
stitcher = cv2.Stitcher.create(cv2.Stitcher_PANORAMA)
stitcher.setPanoConfidenceThresh(0.0) # might be too aggressive for real examples
foo = cv2.imread("/path/to/image1.jpg")
bar = cv2.imread("/path/to/image2.jpg")
status, result = stitcher.stitch((foo,bar))
assert status == 0 # Verify returned status is 'success'
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
I think in this particular case `cv2.Stitcher_SCANS` is a better mode (transformation between images is just a translation), but either `SCANS` or `PANORAMA` works.
|
Try rescaling the images to 0.6 and 0.6 , by using the resize. For some reason I got the result only at those values.
|
64,938,027
|
Can I indicate a specific dictionary shape/form for an argument to a function in python?
Like in typescript I'd indicate that the `info` argument should be an object with a string `name` and a number `age`:
```js
function parseInfo(info: {name: string, age: number}) { /* ... */ }
```
Is there a way to do this with a python function that's otherwise:
```py
def parseInfo(info: dict):
# function body
```
Or is that perhaps not Pythonic and I should use named keywords or something like that?
|
2020/11/20
|
[
"https://Stackoverflow.com/questions/64938027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6826164/"
] |
In Python 3.8+ you could use the [alternative syntax](https://www.python.org/dev/peps/pep-0589/#alternative-syntax) to create a [TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict):
```
from typing import TypedDict
Info = TypedDict('Info', {'name': str, 'age': int})
def parse_info(info: Info):
pass
```
From the documentation on TypedDict:
>
> TypedDict declares a dictionary type that expects all of its instances
> to have a certain set of keys, where each key is associated with a
> value of a consistent type. This expectation is not checked at runtime
> but is only enforced by type checkers.
>
>
>
|
Perhaps you could do the following:
```
def assertTypes(obj, type_obj):
for t in type_obj:
if not(t in obj and type(obj[t]) == type_obj[t]):
return False
return True
def parseInfo(info):
if not assertTypes(info, {"name": str, "age": int}):
print("INVALID OBJECT FORMAT")
return
#continue
```
---
```
>>> parseInfo({"name": "AJ", "age": 8})
>>> parseInfo({"name": "AJ", "age": 'hi'})
INVALID OBJECT FORMAT
>>> parseInfo({"name": "AJ"})
INVALID OBJECT FORMAT
>>> parseInfo({"name": 1, "age": 100})
INVALID OBJECT FORMAT
>>> parseInfo({"name": "Donald", "age": 100})
>>>
```
|
22,328,160
|
I am converting many obscure date formats from an old system. The dates are unpacked/processed as strings and converted into ISO 8601 format.
This particular function attempts to convert YYMMDD0F to YYYYMMDD -- function name says it all. Dates from the year 2000 make this messy and clearly this is not the most pythonic way of handling them. How can I make this better using the `dateutil.parser`?
```
def YYMMDD0FtoYYYYMMDD(date):
YY = date[0:2]
MM = date[2:4]
DD = date[4:6]
if int(YY) >= 78:
YYYY = '19%s' % YY
elif 0 <= int(YY) <= 77 and MM!='' and MM!='00':
YYYY = '20%s' % YY
else:
YYYY = '00%s' % YY
return "%s-%s-%s" % (YYYY, MM, DD)
```
|
2014/03/11
|
[
"https://Stackoverflow.com/questions/22328160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1645914/"
] |
How about this one:
```
SELECT ID, Team, DPV, DPT, DPV-DPT AS Difference FROM e2teams
```
|
Something like this?
```
SELECT
ID,
Team,
DPV,
DPT,
(DPV - DPT) as Difference
FROM
e2teams
```
You can find more information **[here](https://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html)**
|
22,328,160
|
I am converting many obscure date formats from an old system. The dates are unpacked/processed as strings and converted into ISO 8601 format.
This particular function attempts to convert YYMMDD0F to YYYYMMDD -- function name says it all. Dates from the year 2000 make this messy and clearly this is not the most pythonic way of handling them. How can I make this better using the `dateutil.parser`?
```
def YYMMDD0FtoYYYYMMDD(date):
YY = date[0:2]
MM = date[2:4]
DD = date[4:6]
if int(YY) >= 78:
YYYY = '19%s' % YY
elif 0 <= int(YY) <= 77 and MM!='' and MM!='00':
YYYY = '20%s' % YY
else:
YYYY = '00%s' % YY
return "%s-%s-%s" % (YYYY, MM, DD)
```
|
2014/03/11
|
[
"https://Stackoverflow.com/questions/22328160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1645914/"
] |
How about this one:
```
SELECT ID, Team, DPV, DPT, DPV-DPT AS Difference FROM e2teams
```
|
```
SELECT * FROM e2teams GROUP by Difference HAVING (DPV-DPT) = Difference ;
```
|
22,328,160
|
I am converting many obscure date formats from an old system. The dates are unpacked/processed as strings and converted into ISO 8601 format.
This particular function attempts to convert YYMMDD0F to YYYYMMDD -- function name says it all. Dates from the year 2000 make this messy and clearly this is not the most pythonic way of handling them. How can I make this better using the `dateutil.parser`?
```
def YYMMDD0FtoYYYYMMDD(date):
YY = date[0:2]
MM = date[2:4]
DD = date[4:6]
if int(YY) >= 78:
YYYY = '19%s' % YY
elif 0 <= int(YY) <= 77 and MM!='' and MM!='00':
YYYY = '20%s' % YY
else:
YYYY = '00%s' % YY
return "%s-%s-%s" % (YYYY, MM, DD)
```
|
2014/03/11
|
[
"https://Stackoverflow.com/questions/22328160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1645914/"
] |
How about this one:
```
SELECT ID, Team, DPV, DPT, DPV-DPT AS Difference FROM e2teams
```
|
In order to avoid errors and database corruption, you should never have a calculable value on you database.
So the best way to do this is, as answered before :
```
SELECT ID, Team, DPV, DPT, (DPV-DPT) as Difference FROM e2teams
```
|
12,444,942
|
I'm doing an evolution experiment using python and pygame, however that is unimportant, it is one function that is not working and id like you to have a look at.
The error message I'm getting is float object is not callable. It says the problem is in line 205 which is calling the function from line 51.
I will post all my code most of which is irrelevant for fixing this problem. But i think its useful for you guys to have an idea of the code as a whole, and please dont hate me for lack of comments :P it will get there!!
thanks
Link to code: <http://pastebin.com/BBm7Ehax>
|
2012/09/16
|
[
"https://Stackoverflow.com/questions/12444942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339482/"
] |
Line 51:
```
def distance(self,listx,listy):
```
Line 55:
```
self.distance=(((self.x-self.tcentrex)**2) + ((self.y-self.tcentrey)**2))**0.5
```
You can't have `self.distance` be both a method and a variable and expect things to work properly.
When line 55 is executed (during the first time the `distance()` method is called) it overwrites the method (which was at `self.distance`, because it's the method `distance` being called on `self`) with a `float` value.
|
In line 55, within the `distance` method, you assign a float value to `self.distance`. So after you call `distance` once, the attribute `distance` on that object refers to a float, which is not callable.
|
55,174,991
|
Attempting to convert this EGCD equation into python.
```
egcd(a, b) = (1, 0), if b = 0
= (t, s - q * t), otherwise, where
q = a / b (note: integer division)
r = a mod b
(s, t) = egcd(b, r)
```
The test I used was egcd(5, 37) which should return (15,-2) but is returning (19.5, -5.135135135135135)
My code is:
```
def egcd(a, b):
if b == 0:
return (1, 0)
else:
q = a / b # Calculate q
r = a % b # Calculate r
(s,t) = egcd(b,r) # Calculate (s, t) by calling egcd(b, r)
return (t,s-q*t) # Return (t, s-q*t)
```
|
2019/03/15
|
[
"https://Stackoverflow.com/questions/55174991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10687320/"
] |
`a / b` in Python 3 is "true division" the result is non-truncating floating point division even when both operands are `int`s.
To fix, either use `//` instead (which is floor division):
```
q = a // b
```
or [use `divmod`](https://docs.python.org/3/library/functions.html#divmod) to perform both division and remainder as a single computation, replacing both of these lines:
```
q = a / b
r = a % b
```
with just:
```
q, r = divmod(a, b)
```
|
Change `q = a / b` for `q = a // b`
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.